mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): add endpoint for retrieving growth data for the dashboard
This commit is contained in:
@@ -36,6 +36,11 @@ export type Health = {
|
|||||||
oldest_event_ts: number | null
|
oldest_event_ts: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type Growth = {
|
||||||
|
daily: { day: string; users: number; requests: number }[]
|
||||||
|
weekly: { week: string; users: number; requests: number }[]
|
||||||
|
}
|
||||||
|
|
||||||
async function getJSON<T>(path: string): Promise<T> {
|
async function getJSON<T>(path: string): Promise<T> {
|
||||||
const r = await fetch(path, { credentials: 'include' })
|
const r = await fetch(path, { credentials: 'include' })
|
||||||
if (r.status === 401) throw new Error('unauthorized')
|
if (r.status === 401) throw new Error('unauthorized')
|
||||||
@@ -49,3 +54,4 @@ export const fetchUsers = (q = '', sort = 'requests') =>
|
|||||||
getJSON<UserRow[]>(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`)
|
getJSON<UserRow[]>(`/api/dev/users?q=${encodeURIComponent(q)}&sort=${sort}`)
|
||||||
export const fetchLatency = () => getJSON<LatencyRow[]>('/api/dev/latency')
|
export const fetchLatency = () => getJSON<LatencyRow[]>('/api/dev/latency')
|
||||||
export const fetchHealth = () => getJSON<Health>('/api/dev/health')
|
export const fetchHealth = () => getJSON<Health>('/api/dev/health')
|
||||||
|
export const fetchGrowth = () => getJSON<Growth>('/api/dev/growth')
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { StatCards } from '../components/StatCards'
|
|||||||
import { UsersTable } from '../components/UsersTable'
|
import { UsersTable } from '../components/UsersTable'
|
||||||
import { LatencyChart } from '../components/LatencyChart'
|
import { LatencyChart } from '../components/LatencyChart'
|
||||||
import { HealthStrip } from '../components/HealthStrip'
|
import { HealthStrip } from '../components/HealthStrip'
|
||||||
|
import { GrowthChart } from '../components/GrowthChart'
|
||||||
|
|
||||||
const REFRESH_MS = 15_000
|
const REFRESH_MS = 15_000
|
||||||
|
|
||||||
@@ -45,6 +46,9 @@ export function DevScreen() {
|
|||||||
return (
|
return (
|
||||||
<Shell lastRefresh={lastRefresh}>
|
<Shell lastRefresh={lastRefresh}>
|
||||||
{s ? <StatCards s={s} /> : <div className="text-white/40">loading…</div>}
|
{s ? <StatCards s={s} /> : <div className="text-white/40">loading…</div>}
|
||||||
|
<div className="mt-6">
|
||||||
|
<GrowthChart />
|
||||||
|
</div>
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<UsersTable />
|
<UsersTable />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -277,6 +277,63 @@ def query_users(q: str = "", sort: str = "requests", limit: int = 200) -> list[d
|
|||||||
return out[: max(1, min(int(limit), 500))]
|
return out[: max(1, min(int(limit), 500))]
|
||||||
|
|
||||||
|
|
||||||
|
def query_growth(daily_n: int = 30, weekly_n: int = 12) -> dict:
|
||||||
|
"""Per-day and per-week unique users + request counts.
|
||||||
|
|
||||||
|
Powers the /dev dashboard's growth chart. "Users" mirrors the
|
||||||
|
active_users definition in query_summary — any kind in (request,
|
||||||
|
render) counts as active for that bucket. "Requests" counts only
|
||||||
|
kind='request' rows, matching requests_7d.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"daily": [{"day": "YYYY-MM-DD", "users": int, "requests": int}, ...], # oldest -> newest
|
||||||
|
"weekly": [{"week": "GGGG-Www", "users": int, "requests": int}, ...]}
|
||||||
|
"""
|
||||||
|
now = int(time.time())
|
||||||
|
daily_start = now - daily_n * 86400
|
||||||
|
weekly_start = now - weekly_n * 7 * 86400
|
||||||
|
start = min(daily_start, weekly_start)
|
||||||
|
with db.analytics_conn() as c:
|
||||||
|
rows = c.execute(
|
||||||
|
"""SELECT ts, kind, username FROM events
|
||||||
|
WHERE kind IN ('request', 'render') AND ts >= ?""",
|
||||||
|
(start,),
|
||||||
|
).fetchall()
|
||||||
|
daily_buckets: dict[str, dict] = {}
|
||||||
|
weekly_buckets: dict[str, dict] = {}
|
||||||
|
for r in rows:
|
||||||
|
gm = time.gmtime(r["ts"])
|
||||||
|
day = time.strftime("%Y-%m-%d", gm)
|
||||||
|
# %G/%V is ISO-8601 week-numbering year + week, which handles
|
||||||
|
# year-boundary weeks correctly (unlike %Y/%U).
|
||||||
|
week = time.strftime("%G-W%V", gm)
|
||||||
|
for buckets, key in ((daily_buckets, day), (weekly_buckets, week)):
|
||||||
|
b = buckets.setdefault(key, {"requests": 0, "users": set()})
|
||||||
|
if r["kind"] == "request":
|
||||||
|
b["requests"] += 1
|
||||||
|
if r["username"]:
|
||||||
|
b["users"].add(r["username"])
|
||||||
|
daily = []
|
||||||
|
for i in range(daily_n - 1, -1, -1):
|
||||||
|
d = time.strftime("%Y-%m-%d", time.gmtime(now - i * 86400))
|
||||||
|
b = daily_buckets.get(d)
|
||||||
|
daily.append({
|
||||||
|
"day": d,
|
||||||
|
"requests": b["requests"] if b else 0,
|
||||||
|
"users": len(b["users"]) if b else 0,
|
||||||
|
})
|
||||||
|
weekly = []
|
||||||
|
for i in range(weekly_n - 1, -1, -1):
|
||||||
|
wk = time.strftime("%G-W%V", time.gmtime(now - i * 7 * 86400))
|
||||||
|
b = weekly_buckets.get(wk)
|
||||||
|
weekly.append({
|
||||||
|
"week": wk,
|
||||||
|
"requests": b["requests"] if b else 0,
|
||||||
|
"users": len(b["users"]) if b else 0,
|
||||||
|
})
|
||||||
|
return {"daily": daily, "weekly": weekly}
|
||||||
|
|
||||||
|
|
||||||
def query_latency() -> list[dict]:
|
def query_latency() -> list[dict]:
|
||||||
now = int(time.time())
|
now = int(time.time())
|
||||||
week_ago = now - 7 * 86400
|
week_ago = now - 7 * 86400
|
||||||
|
|||||||
@@ -1104,6 +1104,12 @@ def dev_health():
|
|||||||
return jsonify(analytics.query_health())
|
return jsonify(analytics.query_health())
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/dev/growth", methods=["GET"])
|
||||||
|
@auth.require_basic_auth
|
||||||
|
def dev_growth():
|
||||||
|
return jsonify(analytics.query_growth())
|
||||||
|
|
||||||
|
|
||||||
@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
|
||||||
|
|||||||
@@ -121,6 +121,44 @@ def test_query_latency_returns_percentiles(fresh):
|
|||||||
assert by_ep["/<u>"]["p99"] == 99
|
assert by_ep["/<u>"]["p99"] == 99
|
||||||
|
|
||||||
|
|
||||||
|
def test_query_growth_buckets_by_day_and_week(fresh):
|
||||||
|
now = int(time.time())
|
||||||
|
a.ingest_batch([
|
||||||
|
# Today: alice (2 requests), bob (1 request), carol (render only)
|
||||||
|
{"ts": now - 60, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
{"ts": now - 120, "service": "edge", "kind": "request",
|
||||||
|
"username": "alice", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
{"ts": now - 180, "service": "edge", "kind": "request",
|
||||||
|
"username": "bob", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
{"ts": now - 240, "service": "generator", "kind": "render",
|
||||||
|
"username": "carol", "widget": "composite", "latency_ms": 100},
|
||||||
|
# 10 days ago: dave (1 request) — outside the 30d window's start
|
||||||
|
# would still land in the daily bucket if within range
|
||||||
|
{"ts": now - 10 * 86400, "service": "edge", "kind": "request",
|
||||||
|
"username": "dave", "endpoint": "/<u>", "widget": "composite",
|
||||||
|
"status": 200, "latency_ms": 10, "cache_hit": 1},
|
||||||
|
])
|
||||||
|
g = a.query_growth(daily_n=30, weekly_n=12)
|
||||||
|
assert len(g["daily"]) == 30
|
||||||
|
assert len(g["weekly"]) == 12
|
||||||
|
# Today = last entry. Requests count only kind='request', users include
|
||||||
|
# render-only callers — matching active_users_7d's definition.
|
||||||
|
today = g["daily"][-1]
|
||||||
|
assert today["requests"] == 3
|
||||||
|
assert today["users"] == 3 # alice, bob, carol
|
||||||
|
# 10-day-ago bucket has dave's single request
|
||||||
|
ten_days_ago = g["daily"][-11]
|
||||||
|
assert ten_days_ago["requests"] == 1
|
||||||
|
assert ten_days_ago["users"] == 1
|
||||||
|
# Current week (last weekly entry) includes today's traffic
|
||||||
|
assert g["weekly"][-1]["requests"] >= 3
|
||||||
|
assert g["weekly"][-1]["users"] >= 3
|
||||||
|
|
||||||
|
|
||||||
def test_query_health(fresh):
|
def test_query_health(fresh):
|
||||||
now = int(time.time())
|
now = int(time.time())
|
||||||
a.ingest_batch([
|
a.ingest_batch([
|
||||||
|
|||||||
Reference in New Issue
Block a user