feat(edge): add cache-first SVG proxy with Flask-Caching + Flask-Compress

This commit is contained in:
shay
2026-04-17 17:08:37 -04:00
parent 5ba5ec4f4b
commit 4edc66d1bb
3 changed files with 150 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
"""Edge service — cache-first SVG proxy in front of the generator."""
import logging
import requests
from flask import Flask, Response, jsonify
from flask_compress import Compress
from . import cache as cache_mod, config
app = Flask(__name__)
Compress(app)
cache_ext = cache_mod.build_cache(app)
log = logging.getLogger("edge")
def _cache_key(path: str) -> str:
return f"edge:{path}"
def _fetch_origin(path: str) -> requests.Response:
url = f"{config.GENERATOR_URL}/api/{path}"
return requests.get(url, timeout=config.UPSTREAM_TIMEOUT)
@app.route("/health", methods=["GET"])
def health():
ok = True
try:
r = requests.get(f"{config.GENERATOR_URL}/api/health", timeout=config.UPSTREAM_TIMEOUT)
ok = r.status_code == 200
except Exception:
ok = False
return jsonify({"service": "edge", "cache_type": config.CACHE_TYPE, "upstream_ok": ok})
@app.route("/<username>", methods=["GET"])
def serve(username: str):
return _serve(username, path=username)
@app.route("/<username>/<widget>.svg", methods=["GET"])
def serve_widget(username: str, widget: str):
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
def _serve(key_suffix: str, path: str) -> Response:
ck = _cache_key(key_suffix)
cached = cache_ext.get(ck)
if cached is not None:
body, content_type = cached
return Response(body, mimetype=content_type, headers={
"X-Widget-Status": "ready",
"X-Cache": "HIT",
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
})
try:
r = _fetch_origin(path)
except Exception as e:
log.warning("origin unreachable for %s: %s", path, e)
return jsonify({"error": "origin unreachable"}), 503
if r.status_code >= 500:
return jsonify({"error": "origin error"}), 503
status = r.headers.get("X-Widget-Status", "ready")
content_type = r.headers.get("Content-Type", "image/svg+xml")
if status == "ready" and r.status_code == 200:
cache_ext.set(ck, (r.content, content_type), timeout=config.CACHE_DEFAULT_TIMEOUT)
cc = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400"
else:
cc = "no-store"
return Response(r.content, status=r.status_code, mimetype=content_type, headers={
"X-Widget-Status": status,
"X-Cache": "MISS",
"Cache-Control": cc,
})
def main():
app.run(host="0.0.0.0", port=config.PORT)
if __name__ == "__main__":
main()
+16
View File
@@ -0,0 +1,16 @@
"""Flask-Caching config. v1 = SimpleCache (in-process). Swap to RedisCache via env."""
from flask_caching import Cache
from . import config
def build_cache(app) -> Cache:
cfg = {
"CACHE_TYPE": config.CACHE_TYPE,
"CACHE_DEFAULT_TIMEOUT": config.CACHE_DEFAULT_TIMEOUT,
"CACHE_THRESHOLD": config.CACHE_THRESHOLD,
}
if config.CACHE_TYPE == "RedisCache" and config.CACHE_REDIS_URL:
cfg["CACHE_REDIS_URL"] = config.CACHE_REDIS_URL
c = Cache(config=cfg)
c.init_app(app)
return c
+49
View File
@@ -0,0 +1,49 @@
import pytest
import responses
from src import api as apimod
@pytest.fixture
def client(monkeypatch):
monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002")
apimod.cache_ext.clear()
apimod.app.config["TESTING"] = True
with apimod.app.test_client() as c:
yield c
@responses.activate
def test_miss_then_hit_serves_from_cache(client):
responses.add(responses.GET, "http://gen:5002/api/alice",
body=b"<svg>ready</svg>", status=200,
headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"})
r1 = client.get("/alice")
assert r1.status_code == 200
assert r1.data == b"<svg>ready</svg>"
responses.reset()
r2 = client.get("/alice")
assert r2.status_code == 200
assert r2.data == b"<svg>ready</svg>"
@responses.activate
def test_placeholder_not_cached(client):
responses.add(responses.GET, "http://gen:5002/api/alice",
body=b"<svg>building</svg>", status=200,
headers={"X-Widget-Status": "building", "Content-Type": "image/svg+xml"})
r1 = client.get("/alice")
assert r1.status_code == 200
r2 = client.get("/alice")
assert len(responses.calls) == 2
@responses.activate
def test_origin_error_returns_503(client):
responses.add(responses.GET, "http://gen:5002/api/alice", status=500)
r = client.get("/alice")
assert r.status_code == 503
def test_health(client):
r = client.get("/health")
assert r.status_code == 200