diff --git a/AGENTS.md b/AGENTS.md index 9f3bd28..5ede7d2 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 @@ -66,13 +66,13 @@ A client sends a signed `POST /publish` request with a URL and a `post_id`. The │ └── Dockerfile # python:3.14-slim image ├── worker/ │ ├── worker.py # RQ worker entrypoint -│ ├── jobs.py # Pipeline orchestration (deploy_page) +│ ├── jobs.py # Pipeline orchestration (deploy_page) + per-job build report aggregation │ ├── 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. @@ -246,7 +246,8 @@ The worker container uses **Python 3.14**, which is the target version for this - Use type hints where they already appear (e.g. `list[str]`, `pathlib.Path`). - Keep functions focused and document non-obvious behavior in docstrings (the existing code does this extensively). - Log pipeline progress with `print(..., flush=True)` inside worker scripts; these lines become container logs. -- Worker scripts are executed as subprocesses from `jobs.py`; keep CLI interfaces stable (`postprocess.py [...]`, `optimize.py [--no-* flags]`). +- Worker scripts are executed as subprocesses from `jobs.py`; keep CLI interfaces stable (`postprocess.py [...]`, `optimize.py [--no-* flags] [--cache-bucket B --cache-prefix P] [--report PATH]`). +- Internal pipeline artifacts at the workdir root are never uploaded to S3 (deploy.py skips them): `.video-cache-manifest.json` (per-.webm `source-sha256`/`encoder` metadata for the video conversion cache) and `.build-report.json` (per-file optimizer output that jobs.py aggregates into the job result's `report` key). - Prefer `pathlib.Path` for filesystem operations. - When writing regexes for asset discovery, include comments explaining the matched pattern, as done for webpack chunks and Elementor assets. diff --git a/README.md b/README.md index 5d5ff10..92e3138 100644 --- a/README.md +++ b/README.md @@ -136,12 +136,42 @@ While the worker is processing, the status will be `started`. When finished: "post_id": 1, "prefix": "/", "files_uploaded": 12, + "files_skipped": 30, "invalidation_id": null, - "bucket": "my-static-site" + "bucket": "my-static-site", + "report": { + "pages": {"count": 3, "bytes": 210000}, + "assets": { + "images": {"count": 8, "original_bytes": 4200000, "final_bytes": 910000}, + "css": {"count": 2, "original_bytes": 180000, "final_bytes": 41000}, + "js": {"count": 3, "original_bytes": 350000, "final_bytes": 88000}, + "fonts": {"count": 1, "original_bytes": 120000, "final_bytes": 54000}, + "videos": {"count": 1, "original_bytes": 29900000, "final_bytes": 11200000, + "converted": 1, "cache_hits": 0}, + "html": {"count": 3, "original_bytes": 210000, "final_bytes": 64000}, + "other": {"count": 0, "original_bytes": 0, "final_bytes": 0} + }, + "totals": {"files": 18, "original_bytes": 34960000, "final_bytes": 12457000, + "saved_pct": 64.4}, + "steps_seconds": {"scrape": 42.1, "postprocess": 0.8, "optimize": 96.3, "upload": 3.9}, + "top_savings": [ + {"path": "wp-content/uploads/video.webm", "original_bytes": 29900000, + "final_bytes": 11200000} + ] + } } } ``` +The `report` key is the per-job build summary: page count, original → optimized +bytes per asset type (with video conversion/cache-hit counts), total savings, +per-step durations, and the 10 files that saved the most. It is built from a +workdir snapshot taken after postprocessing plus the per-file report that +`optimize.py` writes (`--report`, actions: `converted`, `bundled`, `minified`, +`cached`); files the optimizer did not touch count as unchanged. Jobs enqueue +with a 30-minute timeout so the first (uncached) deploy of video-heavy pages +fits scraping plus ffmpeg encoding. + ### Step 3 — View the published files The dev S3 (LocalStack) has no web console — inspect the bucket with `awslocal` inside the container. Files appear replicating the URL path structure: @@ -373,7 +403,8 @@ X-Signature: "bundle_js": false, "compress_images": false, "compress_html": false, - "convert_fonts": false + "convert_fonts": false, + "convert_videos": false } } ``` @@ -396,6 +427,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..673e62a 100644 --- a/api/main.py +++ b/api/main.py @@ -47,7 +47,7 @@ def _validate_url(url: str) -> None: # --- Infra --- -app = FastAPI(title="Make it Static API", version="1.0.0") +app = FastAPI(title="Make it Static API", version="0.3.0") # CORS: configure allowed origins via CORS_ORIGINS env var (comma-separated). # Defaults to "*" for dev. Restrict in production. @@ -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..1106844 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,151 @@ 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