Skip to content

About

Webhook-driven service that scrapes any page with wget, post-processes and optimizes assets, then publishes a static snapshot to S3 with CloudFront invalidation.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Make It Static

Service that receives a URL via webhook, captures the rendered page (HTML + static assets) with wget, post-processes, optimizes, and publishes to S3 with CloudFront invalidation.


Architecture

Client (any HTTP client, CMS plugin, CI/CD, etc.)
       │  POST /publish  (HMAC-SHA256)
       ▼
   FastAPI ──── enqueue ────► Redis
                                 │
                                 ▼
                              Worker (RQ)
                                 │
                    wget → postprocess → optimize → S3 → CloudFront

Worker pipeline

Step Script What it does
1. Scrape scrape.sh wget captures the page and all static assets
2. Postprocess postprocess.py Removes CMS-specific artifacts, rewrites absolute URLs to relative
3. Optimize optimize.py Bundles local CSS/JS into minified bundles, minifies HTML
4. Upload deploy.py Uploads everything to S3 with correct Content-Type and Cache-Control
5. Invalidate deploy.py Invalidates the CloudFront cache

Components

  • API (FastAPI): receives webhook, validates HMAC, enqueues job. Endpoints: POST /publish, GET /jobs/{id}, DELETE /jobs/{id}, GET /health.
  • Worker (RQ): consumes the queue and runs the full pipeline.
  • Redis: job queue.
  • LocalStack (dev only): local S3 replacement (S3 API on port 4566; bucket auto-created at startup).

Running locally

Prerequisites

  • Docker with Docker Compose v2
  • curl and openssl (to run the test script)

1. Configure the environment

cp .env.example .env

.env.example is already pre-configured to run with LocalStack. No AWS credentials are needed in dev. The only field you may want to adjust is ORIGIN_HOST — it defines which hostname is stripped from URLs in the HTML:

# .env
ORIGIN_HOST=staging.yoursite.com   # origin site domain

2. Start the services

docker network create make-it-static-network
docker compose up --build

Wait for the images to build on the first run. When ready you will see:

worker-1     | RQ Worker started. Waiting for jobs in queue 'deploys'...
api-1        | INFO:     Application startup complete.
localstack-1 | Bucket ready.

Available services:

Service Address
API http://localhost:8123
Site preview http://localhost:8080
LocalStack S3 API http://localhost:4566

3. Check API health

curl http://localhost:8123/health

Expected response:

{"status": "ok", "redis": "ok"}

Running a full test

Step 1 — Publish a page

The test-publish.sh script generates the HMAC signature, builds the payload, and fires the /publish request:

./test-publish.sh https://example.com/

Example output:

[test] payload: {"url":"https://example.com/","post_id":1,"ts":1714230000}
[test] sending to http://localhost:8123/publish
{"job_id":"d3b07384-d113-4e2e-96a8-7b2e3c5f8a21","status":"queued"}

Note the job_id.

Step 2 — Track the job status

curl http://localhost:8123/jobs/<JOB_ID>

While the worker is processing, the status will be started. When finished:

{
  "job_id": "d3b07384-...",
  "status": "finished",
  "result": {
    "ok": true,
    "url": "https://example.com/",
    "post_id": 1,
    "prefix": "/",
    "files_uploaded": 12,
    "files_skipped": 30,
    "invalidation_id": null,
    "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:

docker compose exec localstack awslocal s3 ls s3://my-static-site --recursive

Follow worker logs in real time

docker compose logs -f worker

You will see each pipeline step:

[job] started: url=https://example.com/ post_id=1 workdir=/tmp/deploys/1-20240427-120000
[postprocess] cleaned: /tmp/deploys/1-20240427-120000/index.html
[postprocess] 1 file(s) modified
[optimize] index.html: 48320 → 31204 bytes
[optimize] done — 1 HTML, 3 CSS, 2 JS processed
[job] 12 file(s) uploaded to s3://my-static-site/
[job] OK: {"ok": true, ...}

Running in production (real S3 + CloudFront)

  1. Use docker-compose.prod.yml (without the local S3 stack):

    docker compose -f docker-compose.prod.yml up -d
  2. Adjust .env:

    HMAC_SECRET=$(openssl rand -hex 32)   # generate a new secret
    S3_ENDPOINT_URL=                          # empty = real AWS
    S3_USE_PATH_STYLE=false
    AWS_ACCESS_KEY_ID=<your-key>
    AWS_SECRET_ACCESS_KEY=<your-secret>
    S3_BUCKET=<your-bucket>
    CLOUDFRONT_DISTRIBUTION_ID=E1ABC...
    ORIGIN_HOST=staging.yourdomain.com

    The minimum required IAM policy is in IAM_POLICY.json.

  3. Put the API behind TLS (Caddy, nginx, ALB).

  4. Point your CMS plugin or deployment trigger to this API.


Using published Docker images (WordPress / self-hosted)

Pre-built images are published to Docker Hub:

  • driedel/make-it-static-api
  • driedel/make-it-static-worker

You can add them to an existing Docker Compose project (for example, alongside WordPress) without cloning this repository.

Quick start

  1. Add the services from docker-compose.wordpress.yml to your WordPress docker-compose.yml.

  2. Create or update your .env:

    # HMAC secret shared with the WordPress plugin
    MAKE_IT_STATIC_HMAC_SECRET=$(openssl rand -hex 32)
    
    # S3 credentials
    AWS_ACCESS_KEY_ID=...
    AWS_SECRET_ACCESS_KEY=...
    AWS_REGION=us-east-1
    S3_BUCKET=...
    S3_ENDPOINT_URL=              # leave empty for real AWS
    S3_USE_PATH_STYLE=false       # true for LocalStack (dev), false for AWS
    
    # Optional
    CLOUDFRONT_DISTRIBUTION_ID=...
  3. Start the services:

    docker compose up -d make-it-static-redis make-it-static-api make-it-static-worker
  4. Verify the API:

    curl http://localhost:8123/health
  5. Point your WordPress plugin to http://make-it-static-api:8000/publish (inside the Docker network) or http://localhost:8123/publish from the host.

Required environment variables

Variable Description
MAKE_IT_STATIC_HMAC_SECRET Shared HMAC secret. Must match the secret configured in the WordPress plugin.
AWS_ACCESS_KEY_ID S3 access key.
AWS_SECRET_ACCESS_KEY S3 secret key.
AWS_REGION AWS region (e.g. us-east-1).
S3_BUCKET Target S3 bucket.
S3_ENDPOINT_URL Custom endpoint. Leave empty for AWS. Use http://localstack:4566 for a local LocalStack dev stack.
S3_USE_PATH_STYLE true for LocalStack, false for AWS.

Optional environment variables

Variable Default Description
HMAC_MAX_SKEW 300 Replay tolerance in seconds.
CLOUDFRONT_DISTRIBUTION_ID empty Fallback CloudFront distribution for invalidation.
CORS_ORIGINS * Allowed CORS origins. Restrict in production.

Image tags

  • latest — built from the latest tag or manual workflow run.
  • vX.Y.Z, vX.Y — semantic versions created from Git tags.

Set DOCKERHUB_USERNAME in your .env if you want to pull from a fork under your own Docker Hub account.


Deploying to production — GitHub Actions

The repository includes an example workflow at .github/workflows/deploy.yml. It is disabled by default (manual trigger only) and must be configured before use.

Prerequisites on the EC2 instance

Connect to the instance via SSH and run once:

# Install Docker
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
newgrp docker

# Create the app directory
sudo mkdir -p /opt/make-it-static
sudo chown $USER:$USER /opt/make-it-static

The first deploy (via the workflow) will sync all files into /opt/make-it-static/.

GitHub Secrets

Add the following secrets in Settings → Secrets and variables → Actions:

Secret Description
EC2_HOST Public IP or DNS of the instance (e.g. 1.2.3.4)
EC2_USER SSH user — ubuntu for Ubuntu AMIs, ec2-user for Amazon Linux
EC2_SSH_KEY Full contents of the .pem private key file
ENV_FILE Full contents of the production .env file (see Running in production above)

Security Group

Type Port Source
SSH 22 GitHub Actions IP ranges (or your fixed IP)
HTTPS 443 0.0.0.0/0 (Caddy handles TLS for the API)

Activating automatic deploys

The workflow currently only runs on manual trigger. To deploy automatically on every push to main, edit .github/workflows/deploy.yml and replace:

on:
  workflow_dispatch:

with:

on:
  push:
    branches: ["main"]

CloudFront — critical configuration

Three points that commonly cause issues on the first setup:

  • Origin Access Control (OAC): private bucket, CloudFront accesses via OAC. The bucket policy must allow cloudfront.amazonaws.com with AWS:SourceArn of the distribution.
  • Default Root Object: index.html.
  • CloudFront Function (viewer-request) for directory-style URLs — without it, paths like /blog/my-post/ return 403:
function handler(event) {
  var req = event.request;
  var uri = req.uri;
  if (uri.endsWith('/'))       req.uri = uri + 'index.html';
  else if (!uri.includes('.')) req.uri = uri + '/index.html';
  return req;
}

HTTP contract for /publish — payload fields

Request:

POST /publish
Content-Type: application/json
X-Timestamp: <unix epoch>
X-Signature: <hex hmac-sha256 of raw body>

{
  "url": "<absolute URL>",
  "post_id": <int>,
  "ts": <unix epoch>,
  "cloudfront_distribution_id": "<optional>",
  "extra_cdn": ["<domain1>", "<domain2>"],
  "options": {
    "bundle_css":      false,
    "bundle_js":       false,
    "compress_images": false,
    "compress_html":   false,
    "convert_fonts":   false,
    "convert_videos":  false
  }
}
Field Type Required Description
url string yes Absolute URL of the page to publish
post_id int yes Source content identifier (any integer — used as a job key)
ts int yes Unix epoch — used in HMAC signature
cloudfront_distribution_id string no CloudFront distribution ID; falls back to CLOUDFRONT_DISTRIBUTION_ID env var if absent
extra_cdn string[] no CDN domains present in the HTML that should also be downloaded (e.g. ["cdn.example.com", "assets.lib.io"])
options object no Per-request optimization toggles (all default to true when omitted)

options fields:

Field Type Default Description
bundle_css bool true Bundle and minify local CSS files
bundle_js bool true Bundle and minify local JS files
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:

{"job_id": "abc...", "status": "queued"}

Status query: GET /jobs/{job_id}

Cancellation: DELETE /jobs/{job_id}

The replay window is 300 seconds by default (configurable via HMAC_MAX_SKEW).


Job cancellation — DELETE /jobs/{job_id}

Removes a job from the queue or signals cancellation to the worker, depending on the current state.

Job state Behavior
queued Removes from the queue immediately
started Sends a cancellation signal to the worker (may not interrupt instantly)
finished / failed / others Returns 409 Conflict

Request:

DELETE /jobs/{job_id}

Response (success):

{ "id": "abc...", "cancelled": true, "previous_status": "queued" }

Response (job already finished or failed):

{ "detail": "job cannot be cancelled in status 'finished'" }

Example with curl:

curl -X DELETE http://localhost:8123/jobs/<JOB_ID>

Example with Python:

def cancel_job(job_id: str) -> dict:
    resp = requests.delete(f"{API_URL}/jobs/{job_id}")
    resp.raise_for_status()
    return resp.json()

cancel_job("d3b07384-d113-4e2e-96a8-7b2e3c5f8a21")
# {"id": "d3b07384-...", "cancelled": true, "previous_status": "queued"}

Example call — Python

import hashlib
import hmac
import json
import time

import requests

API_URL = "http://localhost:8123"
HMAC_SECRET = "your-secret-here"  # same value as HMAC_SECRET in .env


def publish_page(
    url: str,
    post_id: int,
    cloudfront_distribution_id: str = "",
    extra_cdn: list[str] | None = None,
    options: dict | None = None,
) -> dict:
    payload = {
        "url": url,
        "post_id": post_id,
        "ts": int(time.time()),
        **({"cloudfront_distribution_id": cloudfront_distribution_id} if cloudfront_distribution_id else {}),
        **({"extra_cdn": extra_cdn} if extra_cdn else {}),
        **({"options": options} if options else {}),
    }
    body = json.dumps(payload, separators=(",", ":")).encode()
    ts = str(int(time.time()))
    sig = hmac.new(HMAC_SECRET.encode(), body, hashlib.sha256).hexdigest()

    resp = requests.post(
        f"{API_URL}/publish",
        data=body,
        headers={
            "Content-Type": "application/json",
            "X-Timestamp": ts,
            "X-Signature": sig,
        },
    )
    resp.raise_for_status()
    return resp.json()


def get_job(job_id: str) -> dict:
    return requests.get(f"{API_URL}/jobs/{job_id}").json()


# Trigger the deploy (disabling image and font processing for this site)
result = publish_page(
    "https://www.yoursite.com/blog/my-post/",
    post_id=42,
    extra_cdn=["cdn.yoursite.com", "assets.lib.io"],
    options={"compress_images": False, "convert_fonts": False},
)
print(result)  # {"job_id": "abc...", "status": "queued"}

# Check the status
status = get_job(result["job_id"])
print(status)  # {"status": "finished", "result": {...}}

Example call — Postman

body

{
  "url": "https://lp.my-website.com.br/subpage/",
  "post_id": 1,
  "ts": 0,
  "extra_cdn": ["cdn.my-website.com.br"],
  "options": {
    "bundle_css": false,
    "bundle_js": false
  }
}

scripts > pre-request

const secret = "your-app-secret-key"; // HMAC_SECRET from your .env
const ts = Math.floor(Date.now() / 1000).toString();

const body = JSON.stringify({
  url: "https://lp.my-website.com.br/subpage/",
  post_id: 1,
  ts: parseInt(ts),
  extra_cdn: ["cdn.my-website.com.br"], // optional — omit if no extra CDN
  options: { bundle_css: false, bundle_js: false }, // optional — omit to use defaults
});

const sig = CryptoJS.HmacSHA256(body, secret).toString(CryptoJS.enc.Hex);

pm.request.body.raw = body;
pm.request.headers.add({ key: "X-Timestamp", value: ts });
pm.request.headers.add({ key: "X-Signature", value: sig });
pm.request.headers.add({ key: "Content-Type", value: "application/json" });

Structure

make-it-static/
├── docker-compose.yml             # dev (with LocalStack)
├── docker-compose.prod.yml        # prod (without LocalStack)
├── docker-compose.wordpress.yml   # example for WordPress integration
├── .env.example
├── IAM_POLICY.json             # minimum IAM policy for the AWS key
├── test-publish.sh             # curl client for manual testing
├── api/
│   ├── main.py                 # FastAPI: /publish, /jobs/{id}, /health
│   └── requirements.txt
└── worker/
    ├── jobs.py                 # pipeline orchestration
    ├── postprocess.py          # HTML cleanup (removes CMS artifacts, rewrites URLs)
    ├── optimize.py             # CSS/JS/HTML bundle + minification
    ├── deploy.py               # S3 upload and CloudFront invalidation
    ├── scrape.sh               # wget wrapper
    └── requirements.txt

About

Webhook-driven service that scrapes any page with wget, post-processes and optimizes assets, then publishes a static snapshot to S3 with CloudFront invalidation.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages