Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
```

Expand Down Expand Up @@ -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.

Expand All @@ -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 <dir> <host> [<cdn>...]`, `optimize.py <dir> [--no-* flags]`).
- Worker scripts are executed as subprocesses from `jobs.py`; keep CLI interfaces stable (`postprocess.py <dir> <host> [<cdn>...]`, `optimize.py <dir> [--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.

Expand Down
42 changes: 40 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -373,7 +403,8 @@ X-Signature: <hex hmac-sha256 of raw body>
"bundle_js": false,
"compress_images": false,
"compress_html": false,
"convert_fonts": false
"convert_fonts": false,
"convert_videos": false
}
}
```
Expand All @@ -396,6 +427,13 @@ X-Signature: <hex hmac-sha256 of raw body>
| `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:**

Expand Down
10 changes: 7 additions & 3 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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(
Expand All @@ -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"}
Expand Down
3 changes: 3 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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():
Expand All @@ -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():
Expand Down
Loading