diff --git a/generator/src/api.py b/generator/src/api.py index db0dc25..eed801a 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -167,6 +167,41 @@ def rate_limited(bucket: str): return deco +def track_request(widget): + """Record one analytics 'request' event per call. `widget` may be a + literal string or a callable taking the route kwargs. + + The endpoint template comes from Flask's matched url_rule; the + username is the route arg or `?username=` query param. Stack ABOVE + @rate_limited so 429s are counted too — rate-limit hits are signal. + """ + def deco(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + t0 = time.monotonic() + resp = fn(*args, **kwargs) + try: + uname = kwargs.get("username") or request.args.get("username") or "" + uname = uname.lower() if isinstance(uname, str) and uname else None + if isinstance(resp, tuple): + status_code = resp[1] if len(resp) > 1 else 200 + else: + status_code = getattr(resp, "status_code", 200) + rule = request.url_rule.rule if request.url_rule else "" + endpoint = rule.replace("", "") + w = widget(kwargs) if callable(widget) else widget + analytics.record_request( + endpoint=endpoint, username=uname, widget=w, + status=int(status_code), + latency_ms=int((time.monotonic() - t0) * 1000), + ) + except Exception: + log.exception("analytics record_request failed") + return resp + return wrapper + return deco + + _STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") @@ -435,7 +470,20 @@ def spa(path: str): # SVG directly. No SPA, no composite — the single widget that README # embeds care about. `/api/` and friends keep working below. if path in ("", "api", "api/") and request.args.get("username"): - return _serve_profile_widget(request.args.get("username", "")) + t0 = time.monotonic() + u = request.args.get("username", "") + resp = _serve_profile_widget(u) + try: + status_code = resp[1] if isinstance(resp, tuple) else getattr(resp, "status_code", 200) + analytics.record_request( + endpoint="/?username=", + username=(u or "").lower() if isinstance(u, str) else None, + widget="grade", status=int(status_code), + latency_ms=int((time.monotonic() - t0) * 1000), + ) + except Exception: + log.exception("analytics record_request failed") + return resp if path.startswith("api/"): return jsonify({"error": "not found"}), 404 if path: @@ -629,6 +677,7 @@ def internal_analytics_events(): @app.route("/api/", methods=["GET"]) +@track_request("composite") @rate_limited("read") def get_widget(username: str): if not is_valid_username(username): @@ -637,6 +686,7 @@ def get_widget(username: str): @app.route("/api//.svg", methods=["GET"]) +@track_request(lambda kw: kw.get("widget")) @rate_limited("read") def get_widget_named(username: str, widget: str): if not is_valid_username(username): @@ -647,6 +697,7 @@ def get_widget_named(username: str, widget: str): @app.route("/api/top-langs", methods=["GET"]) +@track_request("languages") @rate_limited("read") def compat_top_langs(): """Compatibility shim for upstream anuraghazra/github-readme-stats URLs. @@ -688,6 +739,7 @@ def compat_top_langs(): @app.route("/api//data", methods=["GET"]) +@track_request("data") @rate_limited("read") def get_user_data(username: str): """Precomputed widget data for client-side SVG rendering. diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index 3c43837..4cc975c 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -654,3 +654,61 @@ def test_dev_page_serves_html_with_good_creds(client, monkeypatch, tmp_path): r = client.get("/dev", headers=_basic()) # 200 if the bundle is on disk, 503 otherwise — both prove auth passed. assert r.status_code in (200, 503) + + +def test_get_widget_records_request_event(client, monkeypatch): + """Hitting /api/ must emit one analytics 'request' event so the + dashboard's req_7d/top_endpoint/avg_latency columns actually populate + in deployments without an edge in front.""" + from src import analytics + analytics._reset_for_tests() + monkeypatch.setattr(dbmod, "enroll", lambda *a, **kw: {"job_id": None}) + # Enroll the user so /api/ serves a placeholder rather than 4xx; + # status doesn't matter — we only care that an event is recorded. + dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]}) + client.get("/api/alice") + # Drain the in-memory queue (the daemon flush thread isn't running in tests) + analytics.ingest_batch(analytics._drain_queue()) + with dbmod.analytics_conn() as c: + rows = c.execute( + "SELECT username, widget, endpoint, kind FROM events WHERE kind='request'" + ).fetchall() + assert any( + r["username"] == "alice" and r["widget"] == "composite" + and r["endpoint"] == "/api/" + for r in rows + ) + + +def test_get_widget_named_records_endpoint_template(client, monkeypatch): + from src import analytics + analytics._reset_for_tests() + dbmod.enroll("bob", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]}) + client.get("/api/bob/grade.svg") + analytics.ingest_batch(analytics._drain_queue()) + with dbmod.analytics_conn() as c: + rows = c.execute( + "SELECT username, widget, endpoint FROM events WHERE kind='request'" + ).fetchall() + assert any( + r["username"] == "bob" and r["widget"] == "grade" + and r["endpoint"] == "/api//.svg" + for r in rows + ) + + +def test_get_user_data_records_request_event(client, monkeypatch): + from src import analytics + analytics._reset_for_tests() + dbmod.enroll("carol", {"theme": "dark", "enabled": ["grade"], "widget_order": ["grade"]}) + client.get("/api/carol/data") + analytics.ingest_batch(analytics._drain_queue()) + with dbmod.analytics_conn() as c: + rows = c.execute( + "SELECT username, widget, endpoint FROM events WHERE kind='request'" + ).fetchall() + assert any( + r["username"] == "carol" and r["widget"] == "data" + and r["endpoint"] == "/api//data" + for r in rows + )