From 4edc66d1bbf674005a5cf41c67074a5fd13e1d01 Mon Sep 17 00:00:00 2001 From: shay Date: Fri, 17 Apr 2026 17:08:37 -0400 Subject: [PATCH] feat(edge): add cache-first SVG proxy with Flask-Caching + Flask-Compress --- edge/src/api.py | 85 ++++++++++++++++++++++++++++++++++++++++++ edge/src/cache.py | 16 ++++++++ edge/tests/test_api.py | 49 ++++++++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 edge/src/api.py create mode 100644 edge/src/cache.py create mode 100644 edge/tests/test_api.py diff --git a/edge/src/api.py b/edge/src/api.py new file mode 100644 index 0000000..109f5fc --- /dev/null +++ b/edge/src/api.py @@ -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("/", methods=["GET"]) +def serve(username: str): + return _serve(username, path=username) + + +@app.route("//.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() diff --git a/edge/src/cache.py b/edge/src/cache.py new file mode 100644 index 0000000..b6c19ce --- /dev/null +++ b/edge/src/cache.py @@ -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 diff --git a/edge/tests/test_api.py b/edge/tests/test_api.py new file mode 100644 index 0000000..bb22e87 --- /dev/null +++ b/edge/tests/test_api.py @@ -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"ready", 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"ready" + responses.reset() + r2 = client.get("/alice") + assert r2.status_code == 200 + assert r2.data == b"ready" + + +@responses.activate +def test_placeholder_not_cached(client): + responses.add(responses.GET, "http://gen:5002/api/alice", + body=b"building", 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