From e7325459730fca2761f879bf2c185e8a69551d1e Mon Sep 17 00:00:00 2001 From: Danilo Riedel Date: Wed, 25 Nov 2026 11:56:43 -0300 Subject: [PATCH 1/4] feat(worker): convert videos to WebM via ffmpeg with S3 hash cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Video conversion: - The worker image now ships ffmpeg; optimize.py converts non-web video formats (.mov/.m4v/.avi/.mkv/.wmv/.mpg/.mpeg, case-insensitive) to WebM (VP9 CRF 33 + Opus 96k), replacing the original file and rewriting references — the same model already used for images (AVIF) and fonts (WOFF2). .mp4 is left untouched (already web-friendly). - Per-file ffmpeg timeout of 600s; failures keep the original and only warn, so the pipeline never breaks on a bad video. - New convert_videos option (default true) flowing from the API payload through jobs.py to optimize.py's --no-convert-videos flag. S3 hash cache (deploy speed): - sync_to_s3 stores each file's sha256 in the object metadata and skips re-uploading unchanged files (HEAD per file; metadata instead of ETag because multipart uploads make the ETag a composite value). - Converted .webm objects additionally carry source-sha256 and an encoder tag, so repeat deploys of an unchanged video skip the ffmpeg run entirely — the existing .webm in S3 is reused. - The RQ job timeout goes from 600s to 1800s so the first (uncached) deploy of video-heavy pages fits scrape + encoding. Also adds deterministic Content-Types for video extensions in deploy.py, 13 new tests (video conversion, cache hit/miss, upload skip, option wiring), and README/AGENTS.md updates. --- AGENTS.md | 14 +-- README.md | 10 +- api/main.py | 8 +- tests/test_api.py | 3 + tests/test_integration.py | 227 +++++++++++++++++++++++++++++++++++++- tests/test_jobs.py | 32 +++++- tests/test_optimize.py | 32 ++++++ worker/Dockerfile | 1 + worker/deploy.py | 75 ++++++++++++- worker/jobs.py | 19 +++- worker/optimize.py | 208 +++++++++++++++++++++++++++++++++- 11 files changed, 593 insertions(+), 36 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9f3bd28..d0f17c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ A client sends a signed `POST /publish` request with a URL and a `post_id`. The - **API**: Python 3.14, FastAPI 0.165, Uvicorn, Redis, RQ - **Worker**: Python 3.14, RQ, boto3, BeautifulSoup 4, rcssmin, rjsmin, minify-html, fonttools, Pillow -- **External tools inside the worker container**: `wget` (website scraping) +- **External tools inside the worker container**: `wget` (website scraping), `ffmpeg` (video → WebM conversion) - **Queue / cache**: Redis 7 - **Object storage (dev)**: LocalStack (S3-compatible, pinned image `localstack/localstack:4.6.0`) - **Static preview (dev)**: nginx with an `envsubst`-processed template @@ -69,10 +69,10 @@ A client sends a signed `POST /publish` request with a URL and a `post_id`. The │ ├── jobs.py # Pipeline orchestration (deploy_page) │ ├── scrape.sh # wget wrapper │ ├── postprocess.py # HTML cleanup and URL rewriting -│ ├── optimize.py # CSS/JS bundling + minification, image/font conversion -│ ├── deploy.py # S3 upload + CloudFront invalidation +│ ├── optimize.py # CSS/JS bundling + minification, image/font/video conversion +│ ├── deploy.py # S3 upload (sha256 skip of unchanged files) + CloudFront invalidation │ ├── requirements.txt # Worker Python dependencies -│ └── Dockerfile # python:3.14-slim + wget image +│ └── Dockerfile # python:3.14-slim + wget + ffmpeg image ├── tests/ │ ├── conftest.py # pytest path setup and default env vars │ ├── test_api.py # FastAPI endpoint tests @@ -115,8 +115,8 @@ RQ Worker (worker/worker.py) ├── scrape.sh wget captures HTML + static assets ├── jobs.py dynamic CDN / webpack / Elementor asset downloads ├── postprocess.py filename cleanup, URL rewriting, CMS artifact removal - ├── optimize.py CSS/JS bundling + minification, image/font compression - ├── deploy.py S3 upload with Content-Type / Cache-Control + ├── optimize.py CSS/JS bundling + minification, image/font/video compression + ├── deploy.py S3 upload with Content-Type / Cache-Control (skips unchanged files via sha256 metadata) └── deploy.py CloudFront invalidation ``` @@ -234,7 +234,7 @@ The tests mock Redis/RQ and do **not** require a running Redis or Docker stack f - Optimization option flags (`test_jobs.py`, `test_optimize.py`) - CSS/JS bundling and minification (`test_optimize.py`) - Filename normalization, URL rewriting, and HTML absolutization (`test_postprocess.py`) -- S3 upload, CloudFront invalidation, font/image conversion, and subprocess behavior (`test_integration.py`) +- S3 upload (sha256 skip), CloudFront invalidation, font/image/video conversion, and subprocess behavior (`test_integration.py`) The worker container uses **Python 3.14**, which is the target version for this project. Running tests inside Docker avoids host interpreter issues. diff --git a/README.md b/README.md index 5d5ff10..a0e041a 100644 --- a/README.md +++ b/README.md @@ -373,7 +373,8 @@ X-Signature: "bundle_js": false, "compress_images": false, "compress_html": false, - "convert_fonts": false + "convert_fonts": false, + "convert_videos": false } } ``` @@ -396,6 +397,13 @@ X-Signature: | `compress_images` | bool | `true` | Convert raster images to AVIF/WebP | | `compress_html` | bool | `true` | Minify HTML | | `convert_fonts` | bool | `true` | Convert TTF/OTF fonts to WOFF2 | +| `convert_videos` | bool | `true` | Convert non-web videos (MOV/AVI/MKV/WMV/MPG) to WebM (VP9 + Opus) | + +**Deploy caching:** every uploaded S3 object carries its `sha256` in the object +metadata; unchanged files are skipped on repeat deploys (no re-upload). +Converted `.webm` files additionally carry the source video's `source-sha256` +and an `encoder` tag, so a repeat deploy of an unchanged video skips the ffmpeg +conversion entirely — the existing `.webm` in S3 is reused. **Response:** diff --git a/api/main.py b/api/main.py index 77d2f1e..d392cea 100644 --- a/api/main.py +++ b/api/main.py @@ -60,7 +60,10 @@ def _validate_url(url: str) -> None: ) redis_conn = Redis.from_url(REDIS_URL) -queue = Queue("deploys", connection=redis_conn, default_timeout=600) +# 30 min: the first deploy of a video-heavy page must fit the scrape (≤300 s) +# plus ffmpeg encoding; cached repeat deploys finish far below this. +JOB_TIMEOUT = 1800 +queue = Queue("deploys", connection=redis_conn, default_timeout=JOB_TIMEOUT) def verify_signature(raw_body: bytes, sig_header: str, ts_header: str) -> None: @@ -131,6 +134,7 @@ async def publish(req: Request): "compress_images": bool(raw_options.get("compress_images", True)), "compress_html": bool(raw_options.get("compress_html", True)), "convert_fonts": bool(raw_options.get("convert_fonts", True)), + "convert_videos": bool(raw_options.get("convert_videos", True)), } job = queue.enqueue( @@ -140,7 +144,7 @@ async def publish(req: Request): cloudfront_distribution_id, extra_cdn, options, - job_timeout=600, + job_timeout=JOB_TIMEOUT, result_ttl=3600, ) return {"job_id": job.id, "status": "queued"} diff --git a/tests/test_api.py b/tests/test_api.py index 75b7826..6695cb3 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -188,6 +188,7 @@ def test_publish_options_all_false_are_forwarded(): "compress_images": False, "compress_html": False, "convert_fonts": False, + "convert_videos": False, }, } body, headers = _sign(payload) @@ -199,6 +200,7 @@ def test_publish_options_all_false_are_forwarded(): assert options_arg["compress_images"] is False assert options_arg["compress_html"] is False assert options_arg["convert_fonts"] is False + assert options_arg["convert_videos"] is False def test_publish_omitted_options_default_to_true(): @@ -214,6 +216,7 @@ def test_publish_omitted_options_default_to_true(): assert options_arg["compress_images"] is True assert options_arg["compress_html"] is True assert options_arg["convert_fonts"] is True + assert options_arg["convert_videos"] is True def test_publish_partial_options_remaining_default_to_true(): diff --git a/tests/test_integration.py b/tests/test_integration.py index 6843b35..6c9bf17 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1,11 +1,13 @@ """Integration tests — exercise real dependencies (Pillow, fontTools, boto3, subprocess).""" +import shutil import subprocess # nosec B404 from unittest.mock import MagicMock, patch import pytest +from botocore.exceptions import ClientError -from optimize import _convert_fonts, _convert_images, optimize_directory +from optimize import _convert_fonts, _convert_images, _convert_videos, optimize_directory # --------------------------------------------------------------------------- @@ -236,6 +238,149 @@ def test_optimize_directory_full_pipeline(tmp_path): assert len(html_text) < 300 # significantly smaller than original +# --------------------------------------------------------------------------- +# Video conversion (ffmpeg, mocked S3 cache) +# --------------------------------------------------------------------------- + +def _make_test_video(dest) -> None: + """Generates a 1-second .mov clip with ffmpeg (lavfi test source).""" + subprocess.run( # nosec B603 + [ + "ffmpeg", "-nostdin", "-y", + "-f", "lavfi", "-i", "testsrc=duration=1:size=64x64:rate=1", + str(dest), + ], + capture_output=True, + check=True, + ) + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed") +def test_convert_videos_mov_to_webm(tmp_path): + """A .mov is converted to .webm, removed, and the HTML