Branchwell

Glimmer / app · glimmertoday.ai / native / scripts / publish-gallery.py

Raw 11.4 KB on 1e8deb6bbb5f29755b2d53a13ce981eb5be3ab94
1#!/usr/bin/env python3
2"""Publish reviewed Glimmer posters and films to R2, then atomically switch the public catalog."""
3import argparse
4import hashlib
5import json
6import math
7import os
8from pathlib import Path
9import re
10import subprocess
11import sys
12import time
13from urllib.error import HTTPError
14from urllib.request import Request, urlopen
15
16import boto3
17from botocore.config import Config
18from botocore.exceptions import ClientError
19
20BUCKET = "protomota-media"
21PREFIX = "glimmer/gallery/"
22INDEX = "gallery.json"
23CONTENT = "glimmer/content/library-v1.json"
24BASE = "https://media.protomota.com/"
25MEDIA_CACHE = "public, max-age=31536000, immutable"
26INDEX_CACHE = "public, max-age=60, must-revalidate"
27BUNDLED = Path(__file__).resolve().parents[1] / "LibraryContent" / "Gallery"
28ASSET = re.compile(r"v1/[a-z0-9][a-z0-9-]*-([0-9a-f]{16,64})\.(jpg|jpeg|mp4|m4a)")
29TYPES = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "mp4": "video/mp4", "m4a": "audio/mp4"}
30
31
32def validate(data: bytes) -> set[str]:
33 doc = json.loads(data)
34 if len(data) > 1024 * 1024 or doc.get("schemaVersion") != 1 or not isinstance(doc.get("plates"), list) or not doc["plates"]:
35 raise ValueError("Expected a nonempty, schemaVersion 1 gallery catalog under 1 MB")
36 ids, assets = set(), set()
37 for item in doc["plates"]:
38 name = item["id"]
39 if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", name) or name in ids:
40 raise ValueError(f"Duplicate or invalid plate ID: {name!r}")
41 ids.add(name)
42 if not item.get("description", "").strip() or not math.isfinite(item["aspectRatio"]) or item["aspectRatio"] <= 0:
43 raise ValueError(f"{name}: missing accessible description or valid aspect ratio")
44 if "wholeSubject" in item and type(item["wholeSubject"]) is not bool:
45 raise ValueError(f"{name}: wholeSubject must be a boolean")
46 if not item.get("poster") and (item.get("video") or not (BUNDLED / (name + ".jpg")).is_file()):
47 raise ValueError(f"{name}: supply a versioned poster for every film and new plate")
48 for field, extensions in (("video", {"mp4"}), ("poster", {"jpg", "jpeg"}), ("ambience", {"m4a"})):
49 if field not in item:
50 continue
51 match = ASSET.fullmatch(item[field])
52 if not match or match.group(2) not in extensions:
53 raise ValueError(f"{name}: invalid {field} path; use v1/name-<sha256-prefix>.<ext>")
54 assets.add(item[field])
55 return assets
56
57
58def check_film(path: Path) -> None:
59 """Reject a mislabeled file before it can enter an immutable release."""
60 output = subprocess.check_output([
61 "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
62 "stream=width,height,codec_name:stream_side_data=rotation:format=duration", "-of", "json", str(path),
63 ])
64 info = json.loads(output)
65 streams = info.get("streams", [])
66 if not streams:
67 raise ValueError(f"{path.name}: no video track")
68 stream = streams[0]
69 width, height = stream["width"], stream["height"]
70 rotation = next((row["rotation"] for row in stream.get("side_data_list", []) if "rotation" in row), 0)
71 if int(rotation) % 180:
72 width, height = height, width
73 if width <= height or float(info["format"]["duration"]) <= 0:
74 raise ValueError(f"{path.name}: film must have a landscape display frame and a positive duration")
75
76
77def public_check(path: str, expected: str, size: int | None = None, fresh: bool = False, prefix: str = PREFIX) -> None:
78 """Confirm the public CDN bytes before exposing the index. Old referenced files can be verified by hash alone."""
79 url = BASE + prefix + path
80 # A never-before-published index or an update may have a cached predecessor.
81 if fresh:
82 url += "?revision=" + expected
83 is_video = path.endswith(".mp4")
84 if is_video:
85 with urlopen(Request(url, headers={"Range": "bytes=0-1", "User-Agent": "Glimmer-Gallery-Publisher/1"}), timeout=30) as response:
86 if response.status != 206 or not re.fullmatch(r"bytes 0-1/\d+", response.headers.get("Content-Range", "")) or len(response.read(2)) != 2:
87 raise ValueError(f"{path}: CDN does not support a byte-range request")
88 with urlopen(Request(url, headers={"User-Agent": "Glimmer-Gallery-Publisher/1"}), timeout=90) as response:
89 if response.geturl() != url:
90 raise ValueError(f"{path}: unexpected redirect")
91 is_index = path.endswith(".json")
92 wanted = "application/json" if is_index else TYPES[path.rsplit(".", 1)[1]]
93 etag = response.headers.get("ETag")
94 if response.headers.get_content_type() != wanted or not etag:
95 raise ValueError(f"{path}: unexpected MIME type or missing ETag")
96 cache = {directive.strip().lower() for directive in response.headers.get("Cache-Control", "").split(",")}
97 required = (INDEX_CACHE if is_index else MEDIA_CACHE).split(", ")
98 if not set(required) <= cache:
99 raise ValueError(f"{path}: unexpected cache policy {sorted(cache)}")
100 digest = hashlib.sha256()
101 count = 0
102 while chunk := response.read(128 * 1024):
103 count += len(chunk)
104 digest.update(chunk)
105 if not digest.hexdigest().startswith(expected) or (size is not None and size != count):
106 raise ValueError(f"{path}: public content digest or size mismatch")
107 try:
108 with urlopen(Request(url, method="HEAD", headers={"If-None-Match": etag, "User-Agent": "Glimmer-Gallery-Publisher/1"}), timeout=30) as result:
109 raise ValueError(f"{path}: If-None-Match unexpectedly returned {result.status}")
110 except HTTPError as err:
111 if err.code != 304:
112 raise
113 err.close()
114
115
116def code(err: ClientError) -> int:
117 return int(err.response["ResponseMetadata"]["HTTPStatusCode"])
118
119
120def current(s3: object, key: str = PREFIX + INDEX) -> str:
121 try:
122 return s3.head_object(Bucket=BUCKET, Key=key)["ETag"]
123 except ClientError as err:
124 if code(err) == 404:
125 return "absent"
126 raise
127
128
129def main() -> None:
130 args = argparse.ArgumentParser(description=__doc__)
131 args.add_argument("--content", action="store_true", help="Publish the unified editorial library, with the supplied gallery indexed inside")
132 args.add_argument("--status", action="store_true", help="Print the current quoted ETag or absent")
133 args.add_argument("--stage-assets", action="store_true", help="Upload and verify only immutable assets, leaving the public catalog unchanged")
134 args.add_argument("--manifest", type=Path)
135 args.add_argument("--assets", type=Path, help="Directory containing the v1/ folder")
136 args.add_argument("--expected-etag", help="ETag you observed before preparing this revision, or absent for first publication")
137 opts = args.parse_args()
138 endpoint = os.environ["GLIMMER_R2_ENDPOINT"].rstrip("/")
139 if not re.fullmatch(r"https://[0-9a-f]{32}\.r2\.cloudflarestorage\.com", endpoint):
140 raise ValueError("Set GLIMMER_R2_ENDPOINT to the existing R2 account endpoint")
141 s3 = boto3.client("s3", endpoint_url=endpoint, region_name="auto", config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, request_checksum_calculation="when_required"))
142 target = CONTENT if opts.content else PREFIX + INDEX
143 observed = current(s3, target)
144 if opts.status:
145 print(observed)
146 return
147 if not opts.manifest or not opts.assets or not opts.expected_etag:
148 args.error("Publishing requires --manifest, --assets and --expected-etag")
149 if opts.expected_etag != observed:
150 raise ValueError("Catalog changed. Read the latest index and merge your changes before publishing.")
151 data = opts.manifest.read_bytes()
152 if opts.content:
153 edition = json.loads(data)
154 library = edition["content"]
155 bundled = json.loads((BUNDLED.parent / "Catalog.json").read_bytes())
156 lessons = library["lessons"]
157 if (edition.get("schemaVersion") != 1 or len(data) > 2 * 1024 * 1024
158 or set(library) - {"seasonal", "quotes"} != set(bundled) - {"seasonal", "quotes"}
159 or len(lessons) < len(bundled["lessons"])
160 or [item["number"] for item in lessons] != list(range(1, len(lessons) + 1))
161 or len({item["slug"] for item in lessons}) != len(lessons)
162 or any(old["slug"] != new["slug"] or [p["kind"] for p in old["pages"]] != [p["kind"] for p in new["pages"]]
163 for old, new in zip(bundled["lessons"], lessons))):
164 raise ValueError("The edition is incompatible with the bundled library")
165 paths = validate(json.dumps(edition["gallery"]).encode())
166 else:
167 paths = validate(data)
168 delayed: list[tuple[str, str, int]] = []
169 for path in sorted(paths):
170 local = opts.assets / path
171 prefix = ASSET.fullmatch(path).group(1)
172 if local.is_file():
173 if local.suffix == ".mp4":
174 check_film(local)
175 body = local.read_bytes()
176 sha = hashlib.sha256(body).hexdigest()
177 if not sha.startswith(prefix):
178 raise ValueError(f"{path}: local bytes do not match the hash in the filename")
179 try:
180 s3.put_object(Bucket=BUCKET, Key=PREFIX + path, Body=body, IfNoneMatch="*", ContentType=TYPES[local.suffix[1:]], CacheControl=MEDIA_CACHE)
181 except ClientError as err:
182 if code(err) != 412:
183 raise
184 try:
185 public_check(path, sha, len(body))
186 except HTTPError as err:
187 if err.code != 404:
188 raise
189 # A link checker may have cached a 404 just before this first upload.
190 public_check(path, sha, len(body), fresh=True)
191 delayed.append((path, sha, len(body)))
192 else:
193 public_check(path, prefix)
194 for path, sha, size in delayed:
195 deadline = time.monotonic() + 210
196 while True:
197 try:
198 public_check(path, sha, size)
199 break
200 except HTTPError as err:
201 if err.code != 404 or time.monotonic() >= deadline:
202 raise
203 time.sleep(6)
204 if opts.stage_assets:
205 print(f"Staged and verified {len(paths)} remote assets. Catalog still has ETag {current(s3, target)}.")
206 return
207 options = {"IfNoneMatch": "*"} if observed == "absent" else {"IfMatch": observed}
208 try:
209 s3.put_object(Bucket=BUCKET, Key=target, Body=data, ContentType="application/json", CacheControl=INDEX_CACHE, **options)
210 except ClientError as err:
211 if code(err) == 412:
212 raise ValueError("Catalog changed during upload. Fetch and merge the latest index.") from err
213 raise
214 index_sha = hashlib.sha256(data).hexdigest()
215 public_check(target, index_sha, len(data), fresh=True, prefix="")
216 # Unqualified client requests may still have the previous 60-second CDN entry.
217 deadline = time.monotonic() + 100
218 while True:
219 try:
220 public_check(target, index_sha, len(data), prefix="")
221 break
222 except (ValueError, HTTPError):
223 if time.monotonic() >= deadline:
224 raise
225 time.sleep(4)
226 print(f"Verified {len(paths)} referenced remote assets. Published {BASE}{target} with ETag {current(s3, target)}.")
227
228
229if __name__ == "__main__":
230 try:
231 main()
232 except (ValueError, KeyError, ClientError, OSError, subprocess.CalledProcessError) as error:
233 sys.exit(str(error))