Skip to content

Commit d409013

Browse files
committed
build(hooks): fingerprint local script and stylesheet URLs with a content hash
Every local entry of extra_javascript / extra_css is rewritten at build time to `<path>?v=<sha256 prefix>` of the file's content — a changed file is a new URL, an unchanged file keeps the URL it had. docs.magmadevs.com is served through Cloudflare, which caches static assets at the edge for hours and does not know when a deploy happened. With bare paths the first visit after a deploy pins whatever the origin held at that moment for the rest of the TTL: #43 shipped a broken chains-data.js, the first visit cached it, and the fix in #44 six minutes later stayed invisible behind the cached copy. Cloudflare's default cache key includes the query string, so a new hash is a miss by construction. Material's own bundles are already content-hashed; this covers only what this repo ships. External URLs and paths that do not resolve under docs_dir are left untouched.
1 parent f5cab53 commit d409013

3 files changed

Lines changed: 98 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ mkdocs serve # http://127.0.0.1:8000
1919
mkdocs build --strict # output in site/ (gitignored); --strict fails on broken links
2020
```
2121

22+
## Asset URLs are fingerprinted
23+
24+
`hooks/asset_fingerprint.py` rewrites every local `extra_css` / `extra_javascript` entry at
25+
build time to `<path>?v=<sha256 prefix>` of the file's content. The site sits behind
26+
Cloudflare, whose edge caches static assets for hours without knowing when a deploy
27+
happened; a content hash makes a changed file a new URL, so a deploy is visible on the first
28+
request. Nothing to maintain — add the bare path to `mkdocs.yml` and the hook stamps it.
29+
2230
## Deployment
2331

2432
Pushing to `main` triggers [`.github/workflows/docs.yml`](.github/workflows/docs.yml), which builds the

‎hooks/asset_fingerprint.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
"""
2+
MkDocs hook: fingerprint the repo's own scripts and stylesheets.
3+
4+
Every local entry in `extra_javascript` / `extra_css` is rewritten at build
5+
time to carry a content hash — `javascripts/chains-data.js` becomes
6+
`javascripts/chains-data.js?v=3f9c1a2b7e`. A changed file is therefore a new
7+
URL, and an unchanged file keeps the URL it had.
8+
9+
Why: docs.magmadevs.com is served through Cloudflare, which caches static
10+
assets at the edge for hours and does not know when a deploy happened. With
11+
bare paths the first visit after a deploy pins whatever the origin held at
12+
that moment for the rest of the TTL, and a follow-up deploy is invisible until
13+
it expires — a broken chains-data.js shipped that way once and its fix, six
14+
minutes later, stayed hidden for hours. Cloudflare's default cache key
15+
includes the query string, so a new hash is a cache miss by construction.
16+
17+
Material's own bundles are already content-hashed; this covers only what this
18+
repo ships. External URLs (a scheme or a leading `//`) and paths that do not
19+
resolve under docs_dir are left untouched.
20+
21+
Wired via `hooks:` in mkdocs.yml. No manual upkeep.
22+
"""
23+
24+
from __future__ import annotations
25+
26+
import hashlib
27+
import logging
28+
import os
29+
from urllib.parse import urlsplit
30+
31+
log = logging.getLogger("mkdocs.hooks.asset_fingerprint")
32+
33+
# Ten hex chars of SHA-256: unique enough for a handful of files, short enough
34+
# to read in a URL.
35+
_HASH_LEN = 10
36+
37+
38+
def _digest(path: str) -> str:
39+
h = hashlib.sha256()
40+
with open(path, "rb") as fh:
41+
for chunk in iter(lambda: fh.read(1 << 16), b""):
42+
h.update(chunk)
43+
return h.hexdigest()[:_HASH_LEN]
44+
45+
46+
def _fingerprint(raw: str, docs_dir: str) -> str | None:
47+
"""Return `raw` with `?v=<hash>` appended, or None to leave it alone."""
48+
parsed = urlsplit(raw)
49+
if parsed.scheme or parsed.netloc or raw.startswith("//"):
50+
return None # external — not ours to version
51+
if parsed.query or parsed.fragment:
52+
return None # already carries a version (or something deliberate)
53+
local = os.path.join(docs_dir, *parsed.path.split("/"))
54+
if not os.path.isfile(local):
55+
return None # MkDocs will report it, if it reports anything
56+
return f"{raw}?v={_digest(local)}"
57+
58+
59+
def on_config(config):
60+
docs_dir = config["docs_dir"]
61+
stamped: list[str] = []
62+
63+
for i, path in enumerate(config["extra_css"]):
64+
new = _fingerprint(path, docs_dir)
65+
if new is not None:
66+
config["extra_css"][i] = new
67+
stamped.append(new)
68+
69+
for i, script in enumerate(config["extra_javascript"]):
70+
# A plain YAML entry is still a str here; a mapping entry (`path:` +
71+
# `type:`/`defer:`) is an ExtraScriptValue whose `.path` is the URL.
72+
if isinstance(script, str):
73+
new = _fingerprint(script, docs_dir)
74+
if new is not None:
75+
config["extra_javascript"][i] = new
76+
stamped.append(new)
77+
else:
78+
new = _fingerprint(script.path, docs_dir)
79+
if new is not None:
80+
script.path = new
81+
stamped.append(new)
82+
83+
log.info("Fingerprinted %d local asset URL(s)", len(stamped))
84+
for s in stamped:
85+
log.debug(" %s", s)
86+
return config

‎mkdocs.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,12 @@ plugins:
5959
# (the LLM-ingestion corpus) in nav order at post-build, and emits a per-page
6060
# Markdown twin next to each page (URL minus trailing slash + .md) — always in
6161
# sync with content, no manual upkeep. The curated index is docs/llms.txt.
62+
# asset_fingerprint.py appends `?v=<content hash>` to every local entry of
63+
# extra_css / extra_javascript below, so a changed file is a new URL and the
64+
# Cloudflare edge cache in front of the site can never serve a stale copy of it.
6265
hooks:
6366
- hooks/llms_full.py
67+
- hooks/asset_fingerprint.py
6468

6569
# Community / support links — rendered as icons in the footer on every page.
6670
extra:

0 commit comments

Comments
 (0)