mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(admin dashboard): add admin dashboard
This commit is contained in:
@@ -84,4 +84,6 @@ jobs:
|
|||||||
GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }}
|
GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }}
|
||||||
GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }}
|
GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }}
|
||||||
ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }}
|
ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }}
|
||||||
|
DEV_DASHBOARD_USER: ${{ secrets.DEV_DASHBOARD_USER }}
|
||||||
|
DEV_DASHBOARD_PASSWORD: ${{ secrets.DEV_DASHBOARD_PASSWORD }}
|
||||||
run: ./deploy/deploy.sh
|
run: ./deploy/deploy.sh
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
|
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
|
||||||
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
|
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
|
||||||
|
GENERATOR_URL: http://generator:5002
|
||||||
volumes:
|
volumes:
|
||||||
- ${HOME}/ghstats/data/fetcher:/app/data
|
- ${HOME}/ghstats/data/fetcher:/app/data
|
||||||
ports:
|
ports:
|
||||||
@@ -38,6 +39,8 @@ services:
|
|||||||
GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY}
|
GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY}
|
||||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com}
|
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com}
|
||||||
BUILD_VERSION: ${IMAGE_TAG:-}
|
BUILD_VERSION: ${IMAGE_TAG:-}
|
||||||
|
DEV_DASHBOARD_USER: ${DEV_DASHBOARD_USER:?missing DEV_DASHBOARD_USER}
|
||||||
|
DEV_DASHBOARD_PASSWORD: ${DEV_DASHBOARD_PASSWORD:?missing DEV_DASHBOARD_PASSWORD}
|
||||||
volumes:
|
volumes:
|
||||||
- ${HOME}/ghstats/data/generator:/app/data
|
- ${HOME}/ghstats/data/generator:/app/data
|
||||||
ports:
|
ports:
|
||||||
@@ -79,6 +82,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
GENERATOR_URL: http://generator:5002
|
GENERATOR_URL: http://generator:5002
|
||||||
|
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:5003:5003"
|
- "127.0.0.1:5003:5003"
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
+26
-2
@@ -8,12 +8,13 @@ import requests
|
|||||||
from flask import Flask, Response, jsonify, request
|
from flask import Flask, Response, jsonify, request
|
||||||
from flask_compress import Compress
|
from flask_compress import Compress
|
||||||
|
|
||||||
from . import cache as cache_mod, config
|
from . import analytics, cache as cache_mod, config
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
Compress(app)
|
Compress(app)
|
||||||
cache_ext = cache_mod.build_cache(app)
|
cache_ext = cache_mod.build_cache(app)
|
||||||
log = logging.getLogger("edge")
|
log = logging.getLogger("edge")
|
||||||
|
analytics.start_flush_thread()
|
||||||
|
|
||||||
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
|
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
|
||||||
# sync with generator/src/utils/validate.py so invalid paths get rejected
|
# sync with generator/src/utils/validate.py so invalid paths get rejected
|
||||||
@@ -98,6 +99,7 @@ def serve_widget(username: str, widget: str):
|
|||||||
|
|
||||||
|
|
||||||
def _serve(key_suffix: str, path: str) -> Response:
|
def _serve(key_suffix: str, path: str) -> Response:
|
||||||
|
t0 = time.monotonic()
|
||||||
ip = _client_ip()
|
ip = _client_ip()
|
||||||
if not _allow(ip):
|
if not _allow(ip):
|
||||||
return jsonify({"error": "rate_limited"}), 429
|
return jsonify({"error": "rate_limited"}), 429
|
||||||
@@ -106,19 +108,23 @@ def _serve(key_suffix: str, path: str) -> Response:
|
|||||||
cached = cache_ext.get(ck)
|
cached = cache_ext.get(ck)
|
||||||
if cached is not None:
|
if cached is not None:
|
||||||
body, content_type = cached
|
body, content_type = cached
|
||||||
return Response(body, mimetype=content_type, headers={
|
resp = Response(body, mimetype=content_type, headers={
|
||||||
"X-Widget-Status": "ready",
|
"X-Widget-Status": "ready",
|
||||||
"X-Cache": "HIT",
|
"X-Cache": "HIT",
|
||||||
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
|
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
|
||||||
})
|
})
|
||||||
|
_record(path, key_suffix, 200, t0, cache_hit=1)
|
||||||
|
return resp
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r = _fetch_origin(path, ip)
|
r = _fetch_origin(path, ip)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning("origin unreachable for %s: %s", path, e)
|
log.warning("origin unreachable for %s: %s", path, e)
|
||||||
|
_record(path, key_suffix, 503, t0, cache_hit=0)
|
||||||
return jsonify({"error": "origin unreachable"}), 503
|
return jsonify({"error": "origin unreachable"}), 503
|
||||||
|
|
||||||
if r.status_code >= 500:
|
if r.status_code >= 500:
|
||||||
|
_record(path, key_suffix, 503, t0, cache_hit=0)
|
||||||
return jsonify({"error": "origin error"}), 503
|
return jsonify({"error": "origin error"}), 503
|
||||||
|
|
||||||
status = r.headers.get("X-Widget-Status", "ready")
|
status = r.headers.get("X-Widget-Status", "ready")
|
||||||
@@ -129,6 +135,7 @@ def _serve(key_suffix: str, path: str) -> Response:
|
|||||||
else:
|
else:
|
||||||
cc = "no-store"
|
cc = "no-store"
|
||||||
|
|
||||||
|
_record(path, key_suffix, r.status_code, t0, cache_hit=0)
|
||||||
return Response(r.content, status=r.status_code, mimetype=content_type, headers={
|
return Response(r.content, status=r.status_code, mimetype=content_type, headers={
|
||||||
"X-Widget-Status": status,
|
"X-Widget-Status": status,
|
||||||
"X-Cache": "MISS",
|
"X-Cache": "MISS",
|
||||||
@@ -136,6 +143,23 @@ def _serve(key_suffix: str, path: str) -> Response:
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _record(path: str, key_suffix: str, status: int, t0: float, cache_hit: int) -> None:
|
||||||
|
"""Normalize the edge URL into (endpoint_template, username, widget)
|
||||||
|
so the dashboard can group across users without exploding cardinality."""
|
||||||
|
if "/" in key_suffix:
|
||||||
|
username, widget = key_suffix.split("/", 1)
|
||||||
|
endpoint = "/<u>/<widget>.svg"
|
||||||
|
else:
|
||||||
|
username = key_suffix
|
||||||
|
widget = "composite"
|
||||||
|
endpoint = "/<u>"
|
||||||
|
analytics.record_request(
|
||||||
|
endpoint=endpoint, username=username, widget=widget,
|
||||||
|
status=status, latency_ms=int((time.monotonic() - t0) * 1000),
|
||||||
|
cache_hit=cache_hit,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
app.run(host="0.0.0.0", port=config.PORT)
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|
||||||
|
|||||||
@@ -14,3 +14,8 @@ UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
|
|||||||
# default; tighten via env if a specific IP misbehaves.
|
# default; tighten via env if a specific IP misbehaves.
|
||||||
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
|
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
|
||||||
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
|
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
|
||||||
|
|
||||||
|
ANALYTICS_GENERATOR_URL = os.getenv("ANALYTICS_GENERATOR_URL", os.getenv("GENERATOR_URL", "http://localhost:5002"))
|
||||||
|
ANALYTICS_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||||
|
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
|
||||||
|
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
|
||||||
|
|||||||
+19
-1
@@ -3,16 +3,19 @@ import hmac
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import requests
|
import requests
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from flask import Flask, jsonify, request, Response
|
from flask import Flask, jsonify, request, Response
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
from . import config, db, github
|
from . import analytics, config, db, github
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
log = logging.getLogger("fetcher.api")
|
log = logging.getLogger("fetcher.api")
|
||||||
|
|
||||||
|
analytics.start_flush_thread()
|
||||||
|
|
||||||
# Background pool for /fetch-async. The fetch routinely takes 10-20s of
|
# Background pool for /fetch-async. The fetch routinely takes 10-20s of
|
||||||
# wall clock even after parallelization, which is too long to hold an HTTP
|
# wall clock even after parallelization, which is too long to hold an HTTP
|
||||||
# request open from the generator (it would block the worker on its hot
|
# request open from the generator (it would block the worker on its hot
|
||||||
@@ -63,13 +66,18 @@ def get_data(username: str):
|
|||||||
row = db.get_user(username)
|
row = db.get_user(username)
|
||||||
if row is None:
|
if row is None:
|
||||||
# Auto-fetch path
|
# Auto-fetch path
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
|
||||||
log.exception("github fetch failed for %s", username)
|
log.exception("github fetch failed for %s", username)
|
||||||
return jsonify({"error": "fetch_failed"}), 502
|
return jsonify({"error": "fetch_failed"}), 502
|
||||||
if _is_github_not_found(data):
|
if _is_github_not_found(data):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
|
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
|
||||||
|
else:
|
||||||
|
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
|
||||||
h = db.upsert_user(username, data)
|
h = db.upsert_user(username, data)
|
||||||
return jsonify({"data": data, "payload_hash": h, "fetched": True})
|
return jsonify({"data": data, "payload_hash": h, "fetched": True})
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -87,15 +95,20 @@ def force_fetch():
|
|||||||
username = body.get("username")
|
username = body.get("username")
|
||||||
if not _valid_username(username):
|
if not _valid_username(username):
|
||||||
return jsonify({"error": "invalid_username"}), 400
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
except Exception:
|
except Exception:
|
||||||
# Previously returned f"fetch failed: {e}" which leaks internal
|
# Previously returned f"fetch failed: {e}" which leaks internal
|
||||||
# exception text (URLs, stack fragments) across the trust boundary.
|
# exception text (URLs, stack fragments) across the trust boundary.
|
||||||
|
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
|
||||||
log.exception("github fetch failed for %s", username)
|
log.exception("github fetch failed for %s", username)
|
||||||
return jsonify({"error": "fetch_failed"}), 502
|
return jsonify({"error": "fetch_failed"}), 502
|
||||||
if _is_github_not_found(data):
|
if _is_github_not_found(data):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
|
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
|
||||||
|
else:
|
||||||
|
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
|
||||||
old = db.get_user(username)
|
old = db.get_user(username)
|
||||||
old_hash = old["payload_hash"] if old else None
|
old_hash = old["payload_hash"] if old else None
|
||||||
new_hash = db.upsert_user(username, data)
|
new_hash = db.upsert_user(username, data)
|
||||||
@@ -113,13 +126,18 @@ def _bg_fetch(username: str) -> None:
|
|||||||
time out on long fetches.
|
time out on long fetches.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
t0 = time.monotonic()
|
||||||
try:
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
if _is_github_not_found(data):
|
if _is_github_not_found(data):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
|
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
|
||||||
|
else:
|
||||||
|
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
|
||||||
payload_hash = db.upsert_user(username, data)
|
payload_hash = db.upsert_user(username, data)
|
||||||
ok = True
|
ok = True
|
||||||
except Exception:
|
except Exception:
|
||||||
|
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
|
||||||
log.exception("background fetch failed for %s", username)
|
log.exception("background fetch failed for %s", username)
|
||||||
payload_hash = ""
|
payload_hash = ""
|
||||||
ok = False
|
ok = False
|
||||||
|
|||||||
@@ -30,3 +30,6 @@ DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
|
|||||||
# Commit-fetching caps
|
# Commit-fetching caps
|
||||||
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
|
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
|
||||||
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
|
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
|
||||||
|
|
||||||
|
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
|
||||||
|
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import './index.css'
|
|||||||
import { SearchScreen } from './screens/SearchScreen'
|
import { SearchScreen } from './screens/SearchScreen'
|
||||||
import { WorkshopScreen } from './screens/WorkshopScreen'
|
import { WorkshopScreen } from './screens/WorkshopScreen'
|
||||||
import { ResultScreen } from './screens/ResultScreen'
|
import { ResultScreen } from './screens/ResultScreen'
|
||||||
|
import { DevScreen } from './screens/DevScreen'
|
||||||
import { AuthButton } from './components/AuthButton'
|
import { AuthButton } from './components/AuthButton'
|
||||||
import type { WidgetData } from './lib/renderWidgets'
|
import type { WidgetData } from './lib/renderWidgets'
|
||||||
import { DEMO_WIDGET_DATA } from './lib/demoData'
|
import { DEMO_WIDGET_DATA } from './lib/demoData'
|
||||||
@@ -69,6 +70,9 @@ function readWidgetStatus(r: Response): WidgetStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
|
if (typeof window !== 'undefined' && window.location.pathname === '/dev') {
|
||||||
|
return <DevScreen />
|
||||||
|
}
|
||||||
const [me, setMe] = useState<Me>({ login: null })
|
const [me, setMe] = useState<Me>({ login: null })
|
||||||
const [step, setStep] = useState<Step>('search')
|
const [step, setStep] = useState<Step>('search')
|
||||||
const [username, setUsername] = useState('')
|
const [username, setUsername] = useState('')
|
||||||
|
|||||||
+57
-1
@@ -25,7 +25,7 @@ from functools import wraps
|
|||||||
from threading import BoundedSemaphore, Lock
|
from threading import BoundedSemaphore, Lock
|
||||||
from flask import Flask, jsonify, request, Response, send_from_directory, session
|
from flask import Flask, jsonify, request, Response, send_from_directory, session
|
||||||
|
|
||||||
from . import auth, config, db, fetcher_client, placeholder, processor
|
from . import analytics, auth, config, db, fetcher_client, placeholder, processor
|
||||||
from .themes import THEMES
|
from .themes import THEMES
|
||||||
from .utils import is_valid_username, settings_size_ok
|
from .utils import is_valid_username, settings_size_ok
|
||||||
from .widgets import render_grade_widget
|
from .widgets import render_grade_widget
|
||||||
@@ -600,6 +600,21 @@ def internal_data_ready():
|
|||||||
return jsonify({"queued": True, "job_id": job_id}), 200
|
return jsonify({"queued": True, "job_id": job_id}), 200
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/internal/analytics/events", methods=["POST"])
|
||||||
|
def internal_analytics_events():
|
||||||
|
token = request.headers.get("X-Internal-Token", "")
|
||||||
|
if not config.FETCHER_INTERNAL_TOKEN or not hmac.compare_digest(
|
||||||
|
token, config.FETCHER_INTERNAL_TOKEN
|
||||||
|
):
|
||||||
|
return jsonify({"error": "unauthorized"}), 401
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
events = body.get("events", [])
|
||||||
|
if not isinstance(events, list):
|
||||||
|
return jsonify({"error": "bad_request"}), 400
|
||||||
|
n = analytics.ingest_batch(events)
|
||||||
|
return jsonify({"ingested": n})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>", methods=["GET"])
|
@app.route("/api/<username>", methods=["GET"])
|
||||||
@rate_limited("read")
|
@rate_limited("read")
|
||||||
def get_widget(username: str):
|
def get_widget(username: str):
|
||||||
@@ -828,12 +843,15 @@ def _serve_profile_widget(username: str) -> Response:
|
|||||||
payload = result.get("data") or {}
|
payload = result.get("data") or {}
|
||||||
if payload.get("error") == "not_found":
|
if payload.get("error") == "not_found":
|
||||||
return _placeholder_response("not_found", username, theme=theme)
|
return _placeholder_response("not_found", username, theme=theme)
|
||||||
|
t0 = time.monotonic()
|
||||||
grade = processor.compute_grade(
|
grade = processor.compute_grade(
|
||||||
payload,
|
payload,
|
||||||
custom_tags=settings_row["settings"].get("custom_tags"),
|
custom_tags=settings_row["settings"].get("custom_tags"),
|
||||||
)
|
)
|
||||||
ws = (settings_row["settings"].get("widget_settings") or {}).get("grade")
|
ws = (settings_row["settings"].get("widget_settings") or {}).get("grade")
|
||||||
svg = render_grade_widget(grade, theme, settings=ws)
|
svg = render_grade_widget(grade, theme, settings=ws)
|
||||||
|
analytics.record_render(username, "grade",
|
||||||
|
int((time.monotonic() - t0) * 1000))
|
||||||
except Exception:
|
except Exception:
|
||||||
log.exception("profile widget render failed for %s", username)
|
log.exception("profile widget render failed for %s", username)
|
||||||
return _placeholder_response("building", username, theme=theme)
|
return _placeholder_response("building", username, theme=theme)
|
||||||
@@ -957,6 +975,32 @@ def refresh(username: str):
|
|||||||
return jsonify({"refreshed": True, "job_id": job_id})
|
return jsonify({"refreshed": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/dev/summary", methods=["GET"])
|
||||||
|
@auth.require_basic_auth
|
||||||
|
def dev_summary():
|
||||||
|
return jsonify(analytics.query_summary())
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/dev/users", methods=["GET"])
|
||||||
|
@auth.require_basic_auth
|
||||||
|
def dev_users():
|
||||||
|
q = request.args.get("q", "")
|
||||||
|
sort = request.args.get("sort", "requests")
|
||||||
|
return jsonify(analytics.query_users(q=q, sort=sort))
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/dev/latency", methods=["GET"])
|
||||||
|
@auth.require_basic_auth
|
||||||
|
def dev_latency():
|
||||||
|
return jsonify(analytics.query_latency())
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/dev/health", methods=["GET"])
|
||||||
|
@auth.require_basic_auth
|
||||||
|
def dev_health():
|
||||||
|
return jsonify(analytics.query_health())
|
||||||
|
|
||||||
|
|
||||||
@app.errorhandler(413)
|
@app.errorhandler(413)
|
||||||
def _too_large(_e):
|
def _too_large(_e):
|
||||||
return jsonify({"error": "payload_too_large"}), 413
|
return jsonify({"error": "payload_too_large"}), 413
|
||||||
@@ -983,8 +1027,20 @@ def _invalidate_widgets_on_new_build() -> None:
|
|||||||
def main():
|
def main():
|
||||||
db.init_dbs()
|
db.init_dbs()
|
||||||
_invalidate_widgets_on_new_build()
|
_invalidate_widgets_on_new_build()
|
||||||
|
analytics.start_flush_thread()
|
||||||
app.run(host="0.0.0.0", port=config.PORT)
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|
||||||
|
|
||||||
|
def _boot_analytics_for_gunicorn():
|
||||||
|
"""Gunicorn imports the module without calling main(); fire the daemon
|
||||||
|
flush thread here so render timings actually get flushed in production.
|
||||||
|
Idempotent — start_flush_thread checks for a running thread."""
|
||||||
|
try:
|
||||||
|
analytics.start_flush_thread()
|
||||||
|
except Exception:
|
||||||
|
log.exception("analytics boot failed")
|
||||||
|
|
||||||
|
_boot_analytics_for_gunicorn()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
@@ -78,3 +78,43 @@ def require_same_origin(fn):
|
|||||||
return jsonify({"error": "bad_origin"}), 403
|
return jsonify({"error": "bad_origin"}), 403
|
||||||
return fn(*args, **kwargs)
|
return fn(*args, **kwargs)
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hmac as _hmac
|
||||||
|
from functools import wraps as _wraps
|
||||||
|
from flask import jsonify as _jsonify, request as _request
|
||||||
|
|
||||||
|
from . import config as _config
|
||||||
|
|
||||||
|
|
||||||
|
def require_basic_auth(fn):
|
||||||
|
"""HTTP Basic Auth gate for the /dev dashboard. Returns 503 if either
|
||||||
|
credential env var is unset so a missing-secret deploy fails closed.
|
||||||
|
Constant-time comparison on the decoded user+pass concatenation keeps
|
||||||
|
the timing channel narrow without leaking length."""
|
||||||
|
@_wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
u = _config.DEV_DASHBOARD_USER
|
||||||
|
p = _config.DEV_DASHBOARD_PASSWORD
|
||||||
|
if not u or not p:
|
||||||
|
return _jsonify({"error": "dashboard_disabled"}), 503
|
||||||
|
hdr = _request.headers.get("Authorization", "")
|
||||||
|
if not hdr.startswith("Basic "):
|
||||||
|
return _unauth()
|
||||||
|
try:
|
||||||
|
decoded = base64.b64decode(hdr[6:].encode("ascii"), validate=True).decode("utf-8")
|
||||||
|
except Exception:
|
||||||
|
return _unauth()
|
||||||
|
expected = f"{u}:{p}"
|
||||||
|
if not _hmac.compare_digest(decoded, expected):
|
||||||
|
return _unauth()
|
||||||
|
return fn(*args, **kwargs)
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def _unauth():
|
||||||
|
resp = _jsonify({"error": "unauthorized"})
|
||||||
|
resp.status_code = 401
|
||||||
|
resp.headers["WWW-Authenticate"] = 'Basic realm="dev"'
|
||||||
|
return resp
|
||||||
|
|||||||
@@ -118,6 +118,12 @@ TAG_TOPIC_MAP = {
|
|||||||
PORT = int(os.getenv("GENERATOR_PORT", "5002"))
|
PORT = int(os.getenv("GENERATOR_PORT", "5002"))
|
||||||
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
|
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
|
||||||
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
|
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
|
||||||
|
ANALYTICS_DB_PATH = os.getenv("GENERATOR_ANALYTICS_DB_PATH", "./data/analytics.db")
|
||||||
|
ANALYTICS_RETENTION_DAYS = int(os.getenv("ANALYTICS_RETENTION_DAYS", "14"))
|
||||||
|
ANALYTICS_FLUSH_SECONDS = int(os.getenv("ANALYTICS_FLUSH_SECONDS", "5"))
|
||||||
|
ANALYTICS_QUEUE_MAX = int(os.getenv("ANALYTICS_QUEUE_MAX", "2000"))
|
||||||
|
DEV_DASHBOARD_USER = os.getenv("DEV_DASHBOARD_USER", "")
|
||||||
|
DEV_DASHBOARD_PASSWORD = os.getenv("DEV_DASHBOARD_PASSWORD", "")
|
||||||
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
|
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
|
||||||
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
|
||||||
REDIS_URL = os.getenv("REDIS_URL", "")
|
REDIS_URL = os.getenv("REDIS_URL", "")
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from . import config, db, fetcher_client
|
from . import analytics, config, db, fetcher_client
|
||||||
|
|
||||||
log = logging.getLogger("generator.cron")
|
log = logging.getLogger("generator.cron")
|
||||||
|
|
||||||
@@ -47,6 +47,10 @@ def tick() -> dict:
|
|||||||
failed += 1
|
failed += 1
|
||||||
if _TICK_INTER_USER_SLEEP_S > 0:
|
if _TICK_INTER_USER_SLEEP_S > 0:
|
||||||
time.sleep(_TICK_INTER_USER_SLEEP_S)
|
time.sleep(_TICK_INTER_USER_SLEEP_S)
|
||||||
|
try:
|
||||||
|
analytics.prune_old()
|
||||||
|
except Exception:
|
||||||
|
log.exception("analytics prune failed")
|
||||||
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
|
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from . import config
|
|||||||
|
|
||||||
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
|
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
|
||||||
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
|
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
|
||||||
|
ANALYTICS_DB_PATH = config.ANALYTICS_DB_PATH
|
||||||
|
|
||||||
_SETTINGS_SCHEMA = """
|
_SETTINGS_SCHEMA = """
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
@@ -85,6 +86,24 @@ CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
|
|||||||
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
|
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
_ANALYTICS_SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
ts INTEGER NOT NULL,
|
||||||
|
service TEXT NOT NULL,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
username TEXT,
|
||||||
|
endpoint TEXT,
|
||||||
|
widget TEXT,
|
||||||
|
status INTEGER,
|
||||||
|
latency_ms INTEGER NOT NULL,
|
||||||
|
cache_hit INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_events_user_ts ON events(username, ts);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_events_endpoint_ts ON events(endpoint, ts);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _now() -> str:
|
def _now() -> str:
|
||||||
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||||
@@ -123,6 +142,21 @@ def _widgets_conn():
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def analytics_conn():
|
||||||
|
conn = _open(ANALYTICS_DB_PATH)
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_analytics_db() -> None:
|
||||||
|
with analytics_conn() as c:
|
||||||
|
c.executescript(_ANALYTICS_SCHEMA)
|
||||||
|
c.commit()
|
||||||
|
|
||||||
|
|
||||||
def init_dbs() -> None:
|
def init_dbs() -> None:
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
c.executescript(_SETTINGS_SCHEMA)
|
c.executescript(_SETTINGS_SCHEMA)
|
||||||
@@ -138,6 +172,7 @@ def init_dbs() -> None:
|
|||||||
with _widgets_conn() as c:
|
with _widgets_conn() as c:
|
||||||
c.executescript(_WIDGETS_SCHEMA)
|
c.executescript(_WIDGETS_SCHEMA)
|
||||||
c.commit()
|
c.commit()
|
||||||
|
init_analytics_db()
|
||||||
|
|
||||||
|
|
||||||
def settings_hash(settings: dict) -> str:
|
def settings_hash(settings: dict) -> str:
|
||||||
|
|||||||
+10
-1
@@ -13,7 +13,7 @@ import logging
|
|||||||
import time
|
import time
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
|
|
||||||
from . import cache, config, db, fetcher_client, placeholder, processor
|
from . import analytics, cache, config, db, fetcher_client, placeholder, processor
|
||||||
from .widgets import compose_widget
|
from .widgets import compose_widget
|
||||||
|
|
||||||
log = logging.getLogger("generator.worker")
|
log = logging.getLogger("generator.worker")
|
||||||
@@ -53,12 +53,15 @@ def _render_and_persist(username: str, payload: dict, settings: dict, settings_h
|
|||||||
cron-driven worker so embedded widgets keep ticking forward (streak
|
cron-driven worker so embedded widgets keep ticking forward (streak
|
||||||
counter, etc.) as the fetcher refreshes the underlying data — without
|
counter, etc.) as the fetcher refreshes the underlying data — without
|
||||||
waiting for the user to manually click Generate."""
|
waiting for the user to manually click Generate."""
|
||||||
|
t0 = time.monotonic()
|
||||||
widgets = _render_widgets(username, payload, settings)
|
widgets = _render_widgets(username, payload, settings)
|
||||||
db.put_widgets(username, settings_hash, widgets)
|
db.put_widgets(username, settings_hash, widgets)
|
||||||
cache.Cache().delete(
|
cache.Cache().delete(
|
||||||
f"widget:composite:{username}",
|
f"widget:composite:{username}",
|
||||||
*[f"widget:{n}:{username}" for n in widgets],
|
*[f"widget:{n}:{username}" for n in widgets],
|
||||||
)
|
)
|
||||||
|
analytics.record_render(username, "composite",
|
||||||
|
int((time.monotonic() - t0) * 1000))
|
||||||
|
|
||||||
|
|
||||||
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
|
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
|
||||||
@@ -155,7 +158,10 @@ def render_composite_adhoc(username: str, override_settings: dict) -> str | None
|
|||||||
if not payload or payload.get("error") == "not_found":
|
if not payload or payload.get("error") == "not_found":
|
||||||
return None
|
return None
|
||||||
effective = {**settings_row["settings"], **(override_settings or {})}
|
effective = {**settings_row["settings"], **(override_settings or {})}
|
||||||
|
t0 = time.monotonic()
|
||||||
widgets = _render_widgets(username, payload, effective)
|
widgets = _render_widgets(username, payload, effective)
|
||||||
|
analytics.record_render(username, "composite",
|
||||||
|
int((time.monotonic() - t0) * 1000))
|
||||||
return widgets.get("composite")
|
return widgets.get("composite")
|
||||||
|
|
||||||
|
|
||||||
@@ -178,11 +184,14 @@ def render_widgets_now(username: str) -> dict[str, str]:
|
|||||||
cache.Cache().delete(f"widget:composite:{username}")
|
cache.Cache().delete(f"widget:composite:{username}")
|
||||||
return {"composite": svg}
|
return {"composite": svg}
|
||||||
|
|
||||||
|
t0 = time.monotonic()
|
||||||
widgets = _render_widgets(username, payload, settings_row["settings"])
|
widgets = _render_widgets(username, payload, settings_row["settings"])
|
||||||
db.put_widgets(username, settings_row["settings_hash"], widgets)
|
db.put_widgets(username, settings_row["settings_hash"], widgets)
|
||||||
db.point_current_widget(username, settings_row["settings_hash"])
|
db.point_current_widget(username, settings_row["settings_hash"])
|
||||||
c = cache.Cache()
|
c = cache.Cache()
|
||||||
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
|
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
|
||||||
|
analytics.record_render(username, "composite",
|
||||||
|
int((time.monotonic() - t0) * 1000))
|
||||||
log.info("rendered widgets on-demand for %s", username)
|
log.info("rendered widgets on-demand for %s", username)
|
||||||
return widgets
|
return widgets
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ def client(monkeypatch):
|
|||||||
with tempfile.TemporaryDirectory() as d:
|
with tempfile.TemporaryDirectory() as d:
|
||||||
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
|
||||||
dbmod.init_dbs()
|
dbmod.init_dbs()
|
||||||
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
|
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
|
||||||
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
|
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
|
||||||
@@ -536,3 +537,90 @@ def test_per_login_mutate_rate_limit(client, monkeypatch):
|
|||||||
# Third request should be rate-limited.
|
# Third request should be rate-limited.
|
||||||
r3 = client.patch("/api/alice/settings", json={}, headers=h)
|
r3 = client.patch("/api/alice/settings", json={}, headers=h)
|
||||||
assert r3.status_code == 429
|
assert r3.status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
def test_internal_analytics_events_requires_token(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
|
||||||
|
r = client.post("/internal/analytics/events", json={"events": []})
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_internal_analytics_events_ingests(client, monkeypatch):
|
||||||
|
from src import analytics
|
||||||
|
monkeypatch.setattr(cfg, "FETCHER_INTERNAL_TOKEN", "secret")
|
||||||
|
analytics._reset_for_tests()
|
||||||
|
body = {
|
||||||
|
"events": [
|
||||||
|
{"ts": 1700000000, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 12, "cache_hit": 1}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
r = client.post("/internal/analytics/events",
|
||||||
|
headers={"X-Internal-Token": "secret"},
|
||||||
|
json=body)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.get_json()["ingested"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def _basic(user="admin", pw="pw"):
|
||||||
|
import base64
|
||||||
|
return {"Authorization": "Basic " + base64.b64encode(f"{user}:{pw}".encode()).decode()}
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_summary_requires_auth(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
r = client.get("/api/dev/summary")
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_summary_returns_shape(client, monkeypatch):
|
||||||
|
from src import analytics
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
analytics._reset_for_tests()
|
||||||
|
import time as _time
|
||||||
|
analytics.ingest_batch([
|
||||||
|
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 11, "cache_hit": 1},
|
||||||
|
])
|
||||||
|
r = client.get("/api/dev/summary", headers=_basic())
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.get_json()
|
||||||
|
for key in ("requests_7d", "active_users_7d", "p50_ms", "p95_ms",
|
||||||
|
"renders_7d", "avg_render_ms", "daily_requests"):
|
||||||
|
assert key in body
|
||||||
|
assert len(body["daily_requests"]) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_users_endpoint(client, monkeypatch):
|
||||||
|
from src import analytics
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
analytics._reset_for_tests()
|
||||||
|
import time as _time
|
||||||
|
analytics.ingest_batch([
|
||||||
|
{"ts": int(_time.time()) - 60, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 11, "cache_hit": 1},
|
||||||
|
])
|
||||||
|
r = client.get("/api/dev/users", headers=_basic())
|
||||||
|
assert r.status_code == 200
|
||||||
|
rows = r.get_json()
|
||||||
|
assert any(u["username"] == "alice" for u in rows)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_latency_and_health(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
r = client.get("/api/dev/latency", headers=_basic())
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert isinstance(r.get_json(), list)
|
||||||
|
r2 = client.get("/api/dev/health", headers=_basic())
|
||||||
|
assert r2.status_code == 200
|
||||||
|
body = r2.get_json()
|
||||||
|
for key in ("edge_cache_hit_rate", "fetcher_error_rate",
|
||||||
|
"events_dropped_24h"):
|
||||||
|
assert key in body
|
||||||
|
|||||||
@@ -181,3 +181,67 @@ def test_callback_happy_path_sets_session(api_client, monkeypatch):
|
|||||||
assert s["gh_avatar_url"] == "https://x/a.png"
|
assert s["gh_avatar_url"] == "https://x/a.png"
|
||||||
# Row should now exist with github profile populated.
|
# Row should now exist with github profile populated.
|
||||||
assert dbmod.get_settings("alice") is not None
|
assert dbmod.get_settings("alice") is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_basic_auth_503_when_unset(monkeypatch):
|
||||||
|
from flask import Flask, jsonify
|
||||||
|
from src import auth as authmod
|
||||||
|
from src import config as cfg
|
||||||
|
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "")
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.route("/x")
|
||||||
|
@authmod.require_basic_auth
|
||||||
|
def x():
|
||||||
|
return jsonify({"ok": True})
|
||||||
|
|
||||||
|
with app.test_client() as c:
|
||||||
|
r = c.get("/x")
|
||||||
|
assert r.status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_basic_auth_401_on_bad(monkeypatch):
|
||||||
|
import base64
|
||||||
|
from flask import Flask, jsonify
|
||||||
|
from src import auth as authmod
|
||||||
|
from src import config as cfg
|
||||||
|
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.route("/x")
|
||||||
|
@authmod.require_basic_auth
|
||||||
|
def x():
|
||||||
|
return jsonify({"ok": True})
|
||||||
|
|
||||||
|
with app.test_client() as c:
|
||||||
|
r = c.get("/x")
|
||||||
|
assert r.status_code == 401
|
||||||
|
assert r.headers.get("WWW-Authenticate", "").startswith("Basic")
|
||||||
|
bad = base64.b64encode(b"admin:wrong").decode()
|
||||||
|
r2 = c.get("/x", headers={"Authorization": f"Basic {bad}"})
|
||||||
|
assert r2.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_basic_auth_200_on_good(monkeypatch):
|
||||||
|
import base64
|
||||||
|
from flask import Flask, jsonify
|
||||||
|
from src import auth as authmod
|
||||||
|
from src import config as cfg
|
||||||
|
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_USER", "admin")
|
||||||
|
monkeypatch.setattr(cfg, "DEV_DASHBOARD_PASSWORD", "pw")
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.route("/x")
|
||||||
|
@authmod.require_basic_auth
|
||||||
|
def x():
|
||||||
|
return jsonify({"ok": True})
|
||||||
|
|
||||||
|
with app.test_client() as c:
|
||||||
|
good = base64.b64encode(b"admin:pw").decode()
|
||||||
|
r = c.get("/x", headers={"Authorization": f"Basic {good}"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
|||||||
@@ -35,3 +35,24 @@ def test_tick_skips_when_hash_unchanged(tmp_dbs):
|
|||||||
return_value={"data": {}, "payload_hash": "same"}):
|
return_value={"data": {}, "payload_hash": "same"}):
|
||||||
stats = cronmod.tick()
|
stats = cronmod.tick()
|
||||||
assert stats["enqueued"] == 0
|
assert stats["enqueued"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_cron_tick_prunes_old_analytics(tmp_path, monkeypatch):
|
||||||
|
import os, time
|
||||||
|
from src import db as dbmod, analytics, cron
|
||||||
|
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
analytics.ingest_batch([
|
||||||
|
{"ts": int(time.time()) - 30 * 86400, "service": "edge", "kind": "request",
|
||||||
|
"username": "u", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 1, "cache_hit": 1},
|
||||||
|
])
|
||||||
|
# tick() iterates enrolled users but there are none, so it returns
|
||||||
|
# immediately — we only care that the prune call ran.
|
||||||
|
cron.tick()
|
||||||
|
with dbmod.analytics_conn() as c:
|
||||||
|
n = c.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
|
||||||
|
assert n == 0
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ def tmp_dbs(monkeypatch):
|
|||||||
with tempfile.TemporaryDirectory() as d:
|
with tempfile.TemporaryDirectory() as d:
|
||||||
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
|
||||||
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(d, "a.db"))
|
||||||
dbmod.init_dbs()
|
dbmod.init_dbs()
|
||||||
yield d
|
yield d
|
||||||
|
|
||||||
@@ -172,3 +173,15 @@ def test_put_user_streak_upserts(tmp_dbs):
|
|||||||
assert row["current_streak"] == 2
|
assert row["current_streak"] == 2
|
||||||
assert row["max_streak"] == 5
|
assert row["max_streak"] == 5
|
||||||
assert row["max_start"] == "2024-01-01"
|
assert row["max_start"] == "2024-01-01"
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_dbs_creates_analytics_schema(tmp_path, monkeypatch):
|
||||||
|
from src import db as dbmod
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", str(tmp_path / "a.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
with dbmod.analytics_conn() as c:
|
||||||
|
cols = {r["name"] for r in c.execute("PRAGMA table_info(events)").fetchall()}
|
||||||
|
assert cols == {"id", "ts", "service", "kind", "username",
|
||||||
|
"endpoint", "widget", "status", "latency_ms", "cache_hit"}
|
||||||
|
|||||||
@@ -178,3 +178,27 @@ def test_process_one_merges_stored_max(tmp_dbs):
|
|||||||
assert row["max_streak"] == 50
|
assert row["max_streak"] == 50
|
||||||
assert row["max_start"] == "2023-01-01"
|
assert row["max_start"] == "2023-01-01"
|
||||||
assert row["current_streak"] == 2
|
assert row["current_streak"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_one_records_render_event(monkeypatch, tmp_path):
|
||||||
|
import os
|
||||||
|
from src import db as dbmod, worker, analytics, fetcher_client
|
||||||
|
|
||||||
|
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(tmp_path, "s.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(tmp_path, "w.db"))
|
||||||
|
monkeypatch.setattr(dbmod, "ANALYTICS_DB_PATH", os.path.join(tmp_path, "a.db"))
|
||||||
|
dbmod.init_dbs()
|
||||||
|
analytics._reset_for_tests()
|
||||||
|
|
||||||
|
dbmod.enroll("alice", {"theme": "dark",
|
||||||
|
"enabled": ["grade"], "widget_order": ["grade"]})
|
||||||
|
monkeypatch.setattr(fetcher_client, "get_data",
|
||||||
|
lambda u: {"data": {"user": {"login": "alice"}, "repos": [], "events": []},
|
||||||
|
"payload_hash": "h"})
|
||||||
|
monkeypatch.setattr(worker, "_render_widgets",
|
||||||
|
lambda *a, **kw: {"composite": "<svg/>", "grade": "<svg/>"})
|
||||||
|
assert worker.process_one() is True
|
||||||
|
analytics.ingest_batch(analytics._drain_queue())
|
||||||
|
with dbmod.analytics_conn() as c:
|
||||||
|
rows = c.execute("SELECT username, widget, kind FROM events").fetchall()
|
||||||
|
assert ("alice", "composite", "render") in [(r["username"], r["widget"], r["kind"]) for r in rows]
|
||||||
|
|||||||
Reference in New Issue
Block a user