This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathadmin.py
More file actions
1853 lines (1560 loc) · 74.7 KB
/
Copy pathadmin.py
File metadata and controls
1853 lines (1560 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
/admin/* routes — internal admin dashboard with live logs, analytics, GitHub traffic.
Authentication: simple username/password stored in MongoDB ``admin_users`` collection.
Default credentials are seeded on first boot: admin / admin@123
"""
from __future__ import annotations
import asyncio
import base64
import hashlib
import json
import logging
import os
import re
import smtplib
import time
import itertools
from collections import deque
from datetime import datetime, timezone, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import quote, unquote
import httpx
from bson.objectid import ObjectId
from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
from pydantic import BaseModel
from src.config import settings
from src.config.analytics import analytics
from src.database.control_plane_store import control_plane_store
logger = logging.getLogger("xmem.api.admin")
router = APIRouter(prefix="/admin", tags=["admin"])
# ═══════════════════════════════════════════════════════════════════════════
# Admin auth
# ═══════════════════════════════════════════════════════════════════════════
_admin_collection = None
def _get_admin_collection():
global _admin_collection
if _admin_collection is not None:
return _admin_collection
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
client.admin.command("ping")
db = client[settings.mongodb_database]
_admin_collection = db["admin_users"]
# Seed default admin user if collection is empty
if _admin_collection.count_documents({}) == 0:
_admin_collection.insert_one({
"username": "admin",
"password_hash": hashlib.sha256("admin@123".encode()).hexdigest(),
"role": "superadmin",
"created_at": datetime.now(timezone.utc),
})
logger.info("Seeded default admin user (admin / admin@123).")
return _admin_collection
except Exception as exc:
logger.error("Admin MongoDB connection failed: %s", exc)
return None
class AdminLoginRequest(BaseModel):
username: str
password: str
def _verify_admin_token(request: Request) -> Dict[str, Any]:
"""Validate admin session token from cookie or Authorization header."""
token = request.cookies.get("xmem_admin_token")
if not token:
auth = request.headers.get("Authorization", "")
if auth.startswith("Bearer "):
token = auth[7:]
if not token:
raise HTTPException(status_code=401, detail="Not authenticated")
user = control_plane_store.get_admin_session(token)
if not user:
raise HTTPException(status_code=401, detail="Session expired")
return user
# ═══════════════════════════════════════════════════════════════════════════
# Auth endpoints
# ═══════════════════════════════════════════════════════════════════════════
@router.post("/api/login")
async def admin_login(req: AdminLoginRequest):
collection = _get_admin_collection()
if collection is None:
raise HTTPException(status_code=503, detail="Database unavailable")
pwd_hash = hashlib.sha256(req.password.encode()).hexdigest()
user = collection.find_one({"username": req.username, "password_hash": pwd_hash})
if not user:
raise HTTPException(status_code=401, detail="Invalid credentials")
# Generate session token
session = control_plane_store.create_admin_session(
user={"username": user["username"], "role": user.get("role", "admin")},
ttl_seconds=24 * 60 * 60,
)
token = session["token"]
response = JSONResponse({"status": "ok", "token": token, "username": user["username"]})
response.set_cookie(
key="xmem_admin_token",
value=token,
httponly=True,
max_age=86400,
samesite="lax",
)
return response
@router.post("/api/logout")
async def admin_logout(request: Request):
token = request.cookies.get("xmem_admin_token")
if token:
control_plane_store.delete_admin_session(token)
response = JSONResponse({"status": "ok"})
response.delete_cookie("xmem_admin_token")
return response
# ═══════════════════════════════════════════════════════════════════════════
# Live log streaming (WebSocket)
# ═══════════════════════════════════════════════════════════════════════════
# Ring buffer of recent log records
_log_counter = itertools.count()
_log_buffer: deque[Dict[str, Any]] = deque(maxlen=500)
_ws_clients: List[WebSocket] = []
_event_loop: Optional[asyncio.AbstractEventLoop] = None
def _set_event_loop(loop: asyncio.AbstractEventLoop) -> None:
"""Store the main event loop reference for cross-thread access."""
global _event_loop
_event_loop = loop
class WebSocketLogHandler(logging.Handler):
"""Logging handler that pushes records to connected WebSocket clients."""
def emit(self, record: logging.LogRecord) -> None:
entry = {
"id": next(_log_counter),
"ts": datetime.now(timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
if record.exc_info and record.exc_text:
entry["exc"] = record.exc_text
_log_buffer.append(entry)
loop = _event_loop
if loop is None or loop.is_closed():
return
for ws in list(_ws_clients):
try:
asyncio.run_coroutine_threadsafe(
_send_log_safe(ws, entry),
loop
)
except RuntimeError:
pass
async def _send_log_safe(websocket: WebSocket, entry: Dict[str, Any]) -> None:
"""Safely send a log entry to a WebSocket client."""
try:
await websocket.send_json(entry)
except Exception:
pass
# Install the handler on the root logger so ALL logs are captured
_ws_log_handler = WebSocketLogHandler()
_ws_log_handler.setLevel(logging.INFO)
logging.getLogger().addHandler(_ws_log_handler)
logging.getLogger("xmem").addHandler(_ws_log_handler)
logging.getLogger("src").addHandler(_ws_log_handler)
logging.getLogger("uvicorn").addHandler(_ws_log_handler)
logging.getLogger("boto3").setLevel(logging.INFO)
logging.getLogger("botocore").setLevel(logging.INFO)
logging.getLogger("boto3").addHandler(_ws_log_handler)
logging.getLogger("botocore").addHandler(_ws_log_handler)
@router.websocket("/ws/logs")
async def ws_live_logs(websocket: WebSocket):
"""WebSocket endpoint for live log streaming."""
await websocket.accept()
# Capture the running event loop so the log handler can broadcast
_set_event_loop(asyncio.get_running_loop())
# Validate auth token from query param
token = websocket.query_params.get("token", "")
if not token or not control_plane_store.get_admin_session(token):
await websocket.close(code=4001, reason="Not authenticated")
return
_ws_clients.append(websocket)
try:
# Send buffered logs first
for entry in list(_log_buffer):
await websocket.send_json(entry)
# Keep alive — the WebSocketLogHandler.emit() pushes new logs
# via call_soon_threadsafe. We just need to keep the connection
# open by waiting for client messages (or disconnect).
while True:
try:
await asyncio.wait_for(websocket.receive_text(), timeout=30)
except asyncio.TimeoutError:
# Send a lightweight ping to detect broken connections
try:
await websocket.send_json({"type": "ping"})
except Exception:
break
except WebSocketDisconnect:
pass
except Exception:
pass
finally:
if websocket in _ws_clients:
_ws_clients.remove(websocket)
# ═══════════════════════════════════════════════════════════════════════════
# System Logs — journalctl subprocess streamed over SSE (Server-Sent Events)
#
# SSE works over plain HTTP — no WebSocket upgrade needed, so nginx/reverse
# proxies that block WS will NOT break this.
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/system-logs/stream")
async def sse_system_logs(request: Request, user: dict = Depends(_verify_admin_token)):
"""Stream `journalctl -u xmem -f` output as Server-Sent Events.
This is far more reliable than WebSocket because SSE works over regular
HTTP and is not blocked by reverse proxies. It captures ALL service
output (stdout, stderr, crashes, OOM kills, etc.) directly from the
OS journal.
"""
async def _journal_stream():
proc: Optional[asyncio.subprocess.Process] = None
try:
journal_cmd = [
"journalctl", "-u", "xmem", "-f",
"-n", "200", "--no-pager", "-o", "short-iso",
]
# Try without sudo first
proc = await asyncio.create_subprocess_exec(
*journal_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
# Check if we need sudo
try:
first_err = await asyncio.wait_for(proc.stderr.readline(), timeout=2)
err_text = first_err.decode("utf-8", errors="replace").lower()
if "permission" in err_text or "access" in err_text or "denied" in err_text:
proc.terminate()
await proc.wait()
proc = await asyncio.create_subprocess_exec(
"sudo", *journal_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
except asyncio.TimeoutError:
pass # No error = working fine
assert proc and proc.stdout
while True:
# Check if client disconnected
if await request.is_disconnected():
break
try:
line = await asyncio.wait_for(proc.stdout.readline(), timeout=15)
except asyncio.TimeoutError:
# Send SSE keepalive comment to prevent proxy timeout
yield ":keepalive\n\n"
continue
if not line:
# journalctl exited — send error event and stop
yield "event: error\ndata: journalctl process exited\n\n"
break
text = line.decode("utf-8", errors="replace").rstrip("\n")
# SSE format: data: <line>\n\n
yield f"data: {text}\n\n"
except Exception as exc:
logger.error("SSE system logs error: %s", exc)
yield f"event: error\ndata: {exc}\n\n"
finally:
if proc and proc.returncode is None:
try:
proc.terminate()
await asyncio.wait_for(proc.wait(), timeout=3)
except Exception:
proc.kill()
return StreamingResponse(
_journal_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no", # Tell nginx not to buffer
},
)
# ═══════════════════════════════════════════════════════════════════════════
# Gemini pricing (paid tier, per 1M tokens in USD)
# ═══════════════════════════════════════════════════════════════════════════
COST_TABLE: Dict[str, Dict[str, float]] = {
"gemini-embedding-001": {"input": 0.15, "output": 0.00},
"gemini-2.5-flash-lite": {"input": 0.10, "output": 0.40},
"gemini-2.5-flash": {"input": 0.15, "output": 0.60},
"gemini-2.0-flash": {"input": 0.10, "output": 0.40},
"gemini-2.0-flash-lite": {"input": 0.075, "output": 0.30},
}
_PER_M = 1_000_000
def _estimate_cost(model: str, input_tokens: int, output_tokens: int) -> float:
"""Estimate USD cost for a given model and token counts."""
key = model.lower().strip()
prices = COST_TABLE.get(key)
if prices is None:
for prefix, p in COST_TABLE.items():
if key.startswith(prefix):
prices = p
break
if prices is None:
return 0.0
return (input_tokens * prices["input"] + output_tokens * prices["output"]) / _PER_M
# ═══════════════════════════════════════════════════════════════════════════
# Analytics summary API
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/analytics/summary")
async def analytics_summary(request: Request, user: dict = Depends(_verify_admin_token)):
"""Return analytics summaries for the dashboard."""
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
db = client[settings.mongodb_database]
collection = db["analytics"]
now = datetime.now(timezone.utc)
last_24h = now - timedelta(hours=24)
last_7d = now - timedelta(days=7)
# API call stats (last 24h)
api_calls_24h = list(collection.aggregate([
{"$match": {"event": "api_call", "ts": {"$gte": last_24h}}},
{"$group": {
"_id": {"path": "$path", "method": "$method"},
"count": {"$sum": 1},
"avg_latency": {"$avg": "$latency_ms"},
"p95_latency": {"$max": "$latency_ms"}, # approximation
"errors": {"$sum": {"$cond": [{"$gte": ["$status", 400]}, 1, 0]}},
}},
{"$sort": {"count": -1}},
]))
# LLM call stats (last 24h)
llm_stats_24h = list(collection.aggregate([
{"$match": {"event": "llm_call", "ts": {"$gte": last_24h}}},
{"$group": {
"_id": {"provider": "$provider", "model": "$model", "agent": "$agent"},
"count": {"$sum": 1},
"total_input_tokens": {"$sum": "$input_tokens"},
"total_output_tokens": {"$sum": "$output_tokens"},
"total_tokens": {"$sum": "$total_tokens"},
"avg_latency": {"$avg": "$latency_ms"},
"errors": {"$sum": {"$cond": [{"$eq": ["$success", False]}, 1, 0]}},
}},
{"$sort": {"count": -1}},
]))
# Compute cost for each LLM stats row
for row in llm_stats_24h:
model_name = (row.get("_id") or {}).get("model", "")
row["cost_usd"] = round(_estimate_cost(
model_name,
row.get("total_input_tokens", 0),
row.get("total_output_tokens", 0),
), 6)
# Hourly request volume (last 24h)
hourly_volume = list(collection.aggregate([
{"$match": {"event": "api_call", "ts": {"$gte": last_24h}}},
{"$group": {
"_id": {
"hour": {"$hour": "$ts"},
"day": {"$dayOfMonth": "$ts"},
},
"count": {"$sum": 1},
"errors": {"$sum": {"$cond": [{"$gte": ["$status", 400]}, 1, 0]}},
}},
{"$sort": {"_id.day": 1, "_id.hour": 1}},
]))
# Unique users (last 24h)
unique_users = collection.distinct("user_id", {
"event": "api_call", "ts": {"$gte": last_24h}, "user_id": {"$ne": ""},
})
# Total token usage (last 7d)
token_usage_7d = list(collection.aggregate([
{"$match": {"event": "llm_call", "ts": {"$gte": last_7d}}},
{"$group": {
"_id": None,
"total_input": {"$sum": "$input_tokens"},
"total_output": {"$sum": "$output_tokens"},
"total": {"$sum": "$total_tokens"},
"call_count": {"$sum": 1},
}},
]))
# Per-model cost breakdown (last 7d)
cost_by_model_7d = list(collection.aggregate([
{"$match": {"event": "llm_call", "ts": {"$gte": last_7d}}},
{"$group": {
"_id": "$model",
"total_input": {"$sum": "$input_tokens"},
"total_output": {"$sum": "$output_tokens"},
"call_count": {"$sum": 1},
}},
{"$sort": {"total_input": -1}},
]))
total_cost_7d = 0.0
for row in cost_by_model_7d:
model_name = row.get("_id") or ""
cost = _estimate_cost(model_name, row.get("total_input", 0), row.get("total_output", 0))
row["cost_usd"] = round(cost, 6)
total_cost_7d += cost
if token_usage_7d:
token_usage_7d[0]["total_cost_usd"] = round(total_cost_7d, 6)
# Daily LLM calls (last 7d) for chart
daily_llm = list(collection.aggregate([
{"$match": {"event": "llm_call", "ts": {"$gte": last_7d}}},
{"$group": {
"_id": {
"year": {"$year": "$ts"},
"month": {"$month": "$ts"},
"day": {"$dayOfMonth": "$ts"},
},
"count": {"$sum": 1},
"tokens": {"$sum": "$total_tokens"},
}},
{"$sort": {"_id.year": 1, "_id.month": 1, "_id.day": 1}},
]))
return JSONResponse({
"api_calls_24h": _bson_safe(api_calls_24h),
"llm_stats_24h": _bson_safe(llm_stats_24h),
"hourly_volume": _bson_safe(hourly_volume),
"unique_users_24h": len(unique_users),
"token_usage_7d": _bson_safe(token_usage_7d[0] if token_usage_7d else {}),
"daily_llm_calls": _bson_safe(daily_llm),
"cost_by_model_7d": _bson_safe(cost_by_model_7d),
"cost_table": COST_TABLE,
})
except Exception as exc:
logger.exception("Analytics summary failed")
return JSONResponse({"error": str(exc)}, status_code=500)
# ═══════════════════════════════════════════════════════════════════════════
# GitHub traffic API
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/github/traffic")
async def github_traffic(request: Request, user: dict = Depends(_verify_admin_token)):
"""Fetch GitHub traffic data (views, clones, referrers, paths)."""
token = settings.github_token
owner = settings.github_repo_owner
repo = settings.github_repo_name
if not token:
return JSONResponse({"error": "GITHUB_TOKEN not configured"}, status_code=400)
# Use Bearer format for OAuth tokens (Fine-grained PATs) or token format for classic PATs
# Try Bearer first (modern format), fallback logic handles both
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
"X-GitHub-Api-Version": "2022-11-28",
}
base_url = f"https://api.github.com/repos/{owner}/{repo}"
# Create client without SSL_CERT_FILE env interference
ssl_context = httpx.create_ssl_context(verify=True, trust_env=False)
async with httpx.AsyncClient(timeout=15, verify=ssl_context) as client:
results = {}
endpoints = {
"views": f"{base_url}/traffic/views",
"clones": f"{base_url}/traffic/clones",
"referrers": f"{base_url}/traffic/popular/referrers",
"paths": f"{base_url}/traffic/popular/paths",
"stars": f"{base_url}",
}
for key, url in endpoints.items():
try:
resp = await client.get(url, headers=headers)
if resp.status_code == 200:
results[key] = resp.json()
else:
# Log detailed error for debugging
error_body = resp.text[:500] if resp.text else "No response body"
logger.warning(f"GitHub API {key} failed: HTTP {resp.status_code} - {error_body}")
results[key] = {"error": f"HTTP {resp.status_code}", "details": error_body}
except Exception as exc:
logger.exception(f"GitHub API {key} exception")
results[key] = {"error": str(exc)}
return JSONResponse(results)
@router.get("/api/github/config-debug")
async def github_config_debug(request: Request, user: dict = Depends(_verify_admin_token)):
"""Debug endpoint to verify GitHub settings are loaded (does not expose full token)."""
token = settings.github_token
owner = settings.github_repo_owner
repo = settings.github_repo_name
return JSONResponse({
"token_configured": bool(token),
"token_prefix": token[:10] + "..." if token and len(token) > 10 else "N/A",
"token_length": len(token) if token else 0,
"owner": owner,
"repo": repo,
"full_repo_path": f"{owner}/{repo}" if owner and repo else "N/A",
"hint": "If token shows as 'N/A', check your .env file has GITHUB_TOKEN and restart the server.",
})
@router.get("/api/analytics/recent-events")
async def analytics_recent_events(request: Request, user: dict = Depends(_verify_admin_token), limit: int = 20):
"""Debug endpoint to see recent analytics events (including LLM calls)."""
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
db = client[settings.mongodb_database]
collection = db["analytics"]
# Get recent events of all types
events = list(collection.find(
{},
{"_id": 0}
).sort("ts", -1).limit(limit))
# Get counts by event type
event_counts = list(collection.aggregate([
{"$group": {"_id": "$event", "count": {"$sum": 1}}}
]))
# Get recent LLM calls specifically
llm_calls = list(collection.find(
{"event": "llm_call"},
{"_id": 0}
).sort("ts", -1).limit(10))
return JSONResponse({
"event_counts": _bson_safe(event_counts),
"recent_llm_calls": _bson_safe(llm_calls),
"recent_events": _bson_safe(events),
"analytics_queue_size": len(getattr(analytics, '_queue', [])),
})
except Exception as exc:
logger.exception("Failed to fetch recent events")
return JSONResponse({"error": str(exc)}, status_code=500)
# ═══════════════════════════════════════════════════════════════════════════
# Server metrics API
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/server/metrics")
async def server_metrics(request: Request, user: dict = Depends(_verify_admin_token)):
"""Return current server metrics (uptime, pipeline status, etc.)."""
from src.api.dependencies import get_init_error, get_startup_time, is_ready
uptime = round(time.time() - get_startup_time(), 1) if get_startup_time() else 0
return JSONResponse({
"uptime_seconds": uptime,
"pipelines_ready": is_ready(),
"init_error": get_init_error(),
"environment": settings.environment,
"sentry_enabled": bool(settings.sentry_dsn),
"prometheus_enabled": settings.enable_prometheus,
"analytics_enabled": settings.enable_analytics,
})
# ═══════════════════════════════════════════════════════════════════════════
# Recent logs API (for initial page load)
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/logs/recent")
async def recent_logs(request: Request, user: dict = Depends(_verify_admin_token), since_id: int = -1):
"""Return log entries from the ring buffer.
If ``since_id`` is provided, only entries with id > since_id are returned,
enabling efficient incremental HTTP polling as a fallback when WebSocket
connections are blocked by reverse proxies.
"""
if since_id >= 0:
entries = [e for e in _log_buffer if e.get("id", -1) > since_id]
else:
entries = list(_log_buffer)
return JSONResponse(entries)
@router.post("/api/analytics/test-llm-track")
async def test_llm_track(request: Request, user: dict = Depends(_verify_admin_token)):
"""Test endpoint to manually trigger an LLM analytics event."""
import random
test_providers = ["gemini", "openai", "claude", "bedrock"]
test_models = ["gemini-2.5-flash", "gpt-4.1-mini", "claude-3-5-sonnet", "nova-lite"]
analytics.track_llm_call(
provider=random.choice(test_providers),
model=random.choice(test_models),
agent="test-agent",
latency_ms=123.45,
input_tokens=random.randint(100, 500),
output_tokens=random.randint(50, 200),
total_tokens=random.randint(150, 700),
success=True,
)
return JSONResponse({
"status": "ok",
"message": "Test LLM call tracked. Check /admin/api/analytics/summary or /admin/api/analytics/recent-events to verify.",
"queue_size": len(getattr(analytics, '_queue', [])),
})
# ═══════════════════════════════════════════════════════════════════════════
# Scanner analytics endpoints
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/scanner/analytics")
async def scanner_analytics(request: Request, user: dict = Depends(_verify_admin_token)):
"""Return scanner analytics from all scanner collections."""
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
db = client[settings.mongodb_database]
# Collection references
scan_runs = db["scan_runs"]
scanner_jobs = db["scanner_jobs"]
scanner_user_repos = db["scanner_user_repos"]
scanner_index_visibility = db["scanner_index_visibility"]
scanner_community_stars = db["scanner_community_stars"]
# 1. Scan Runs stats
scan_runs_count = scan_runs.count_documents({})
scan_runs_latest = list(scan_runs.find({}, {"_id": 0, "org_id": 1, "repo": 1, "last_sha": 1, "last_scanned_at": 1, "status": 1})
.sort("last_scanned_at", -1)
.limit(10))
# 2. Scanner Jobs stats
scanner_jobs_count = scanner_jobs.count_documents({})
jobs_by_status = list(scanner_jobs.aggregate([
{"$group": {"_id": {"phase1": "$phase1_status", "phase2": "$phase2_status"}, "count": {"$sum": 1}}}
]))
recent_jobs = list(scanner_jobs.find(
{},
{"_id": 0, "job_id": 1, "username": 1, "org": 1, "repo": 1, "branch": 1,
"phase1_status": 1, "phase2_status": 1, "updated_at": 1, "error": 1}
).sort("updated_at", -1).limit(20))
# 3. User Repos stats
user_repos_count = scanner_user_repos.count_documents({})
repos_per_user = list(scanner_user_repos.aggregate([
{"$group": {"_id": "$username", "repo_count": {"$sum": 1}}},
{"$sort": {"repo_count": -1}},
{"$limit": 10}
]))
recent_repos = list(scanner_user_repos.find(
{},
{"_id": 0, "username": 1, "github_org": 1, "repo": 1, "branch": 1, "last_seen_commit": 1}
).sort("_id", -1).limit(20))
# 4. Index Visibility stats
visibility_count = scanner_index_visibility.count_documents({})
visibility_breakdown = list(scanner_index_visibility.aggregate([
{"$group": {"_id": "$is_visible", "count": {"$sum": 1}}}
]))
# 5. Community Stars stats
stars_count = scanner_community_stars.count_documents({})
top_starred_repos = list(scanner_community_stars.aggregate([
{"$group": {"_id": {"org": "$org_id", "repo": "$repo"}, "star_count": {"$sum": 1}}},
{"$sort": {"star_count": -1}},
{"$limit": 10}
]))
# Unique users who starred
unique_stargazers = scanner_community_stars.distinct("username")
return JSONResponse({
"scan_runs": {
"total": scan_runs_count,
"latest": _bson_safe(scan_runs_latest),
},
"scanner_jobs": {
"total": scanner_jobs_count,
"by_status": _bson_safe(jobs_by_status),
"recent": _bson_safe(recent_jobs),
},
"user_repos": {
"total": user_repos_count,
"per_user": _bson_safe(repos_per_user),
"recent": _bson_safe(recent_repos),
},
"index_visibility": {
"total": visibility_count,
"breakdown": _bson_safe(visibility_breakdown),
},
"community_stars": {
"total_stars": stars_count,
"unique_users": len(unique_stargazers),
"top_repos": _bson_safe(top_starred_repos),
},
})
except Exception as exc:
logger.exception("Scanner analytics failed")
return JSONResponse({"error": str(exc)}, status_code=500)
# ═══════════════════════════════════════════════════════════════════════════
# Users management endpoints
# ═══════════════════════════════════════════════════════════════════════════
@router.get("/api/users")
async def list_users(request: Request, user: dict = Depends(_verify_admin_token)):
"""Return list of all users with their details and API key counts."""
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
db = client[settings.mongodb_database]
users_collection = db["users"]
api_keys_collection = db["api_keys"]
# Fetch all users
users = list(users_collection.find({}, {
"_id": 1,
"email": 1,
"name": 1,
"google_id": 1,
"picture": 1,
"username": 1,
"created_at": 1,
"last_login": 1,
}).sort("created_at", -1))
# Get API key counts per user
user_ids = [str(u["_id"]) for u in users]
api_key_counts = {}
if user_ids:
pipeline = [
{"$match": {"user_id": {"$in": user_ids}}},
{"$group": {"_id": "$user_id", "count": {"$sum": 1}}}
]
for doc in api_keys_collection.aggregate(pipeline):
api_key_counts[doc["_id"]] = doc["count"]
# Format response
formatted_users = []
for u in users:
user_id = str(u["_id"])
formatted_users.append({
"id": user_id,
"email": u.get("email", ""),
"name": u.get("name", ""),
"google_id": u.get("google_id", ""),
"picture": u.get("picture", ""),
"username": u.get("username", None),
"created_at": u.get("created_at"),
"last_login": u.get("last_login"),
"api_key_count": api_key_counts.get(user_id, 0),
})
return JSONResponse({
"users": _bson_safe(formatted_users),
"total_users": len(formatted_users),
})
except Exception as exc:
logger.exception("Failed to fetch users list")
return JSONResponse({"error": str(exc)}, status_code=500)
@router.get("/api/users/{user_id}/trail")
async def get_user_trail(
request: Request,
user_id: str,
user: dict = Depends(_verify_admin_token),
hours: int = 24,
limit: int = 50
):
"""Return API call trail for a specific user from analytics data.
Args:
user_id: The user ID to fetch trail for
hours: How many hours back to look (default: 24)
limit: Maximum number of trail entries (default: 50)
"""
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
db = client[settings.mongodb_database]
users_collection = db["users"]
analytics_collection = db["analytics"]
# Fetch user details
user_doc = users_collection.find_one({"_id": user_id})
if not user_doc:
# Try finding by string ID
from bson.objectid import ObjectId
try:
user_doc = users_collection.find_one({"_id": ObjectId(user_id)})
except Exception:
pass
if not user_doc:
raise HTTPException(status_code=404, detail="User not found")
user_email = user_doc.get("email", "")
user_name = user_doc.get("name", "")
# Calculate time range
now = datetime.now(timezone.utc)
since = now - timedelta(hours=hours)
# Fetch recent API calls for this user
# Try matching by user_id in various formats
trail_query = {
"event": "api_call",
"ts": {"$gte": since},
"$or": [
{"user_id": user_id},
{"user_id": str(user_doc.get("_id", ""))},
{"user_id": user_doc.get("email", "")},
]
}
trail = list(analytics_collection.find(
trail_query,
{"_id": 0, "path": 1, "method": 1, "status": 1, "latency_ms": 1, "ts": 1, "user_id": 1}
).sort("ts", -1).limit(limit))
# Get unique paths accessed
unique_paths = list(set(t.get("path", "") for t in trail if t.get("path")))
# Get total calls in the period
total_calls = analytics_collection.count_documents(trail_query)
# Get calls in last 24h specifically
trail_24h_query = {
"event": "api_call",
"ts": {"$gte": now - timedelta(hours=24)},
"$or": [
{"user_id": user_id},
{"user_id": str(user_doc.get("_id", ""))},
{"user_id": user_doc.get("email", "")},
]
}
total_calls_24h = analytics_collection.count_documents(trail_24h_query)
return JSONResponse({
"user_id": user_id,
"user_email": user_email,
"user_name": user_name,
"trail": _bson_safe(trail),
"unique_paths": sorted(unique_paths),
"total_calls_period": total_calls,
"total_calls_24h": total_calls_24h,
"period_hours": hours,
})
except HTTPException:
raise
except Exception as exc:
logger.exception("Failed to fetch user trail")
return JSONResponse({"error": str(exc)}, status_code=500)
# ═══════════════════════════════════════════════════════════════════════════
# Outreach — GitHub email scraper + email sender with tracking
# ═══════════════════════════════════════════════════════════════════════════
_outreach_db = None
_scrape_tasks: Dict[str, asyncio.Task] = {}
_scrape_stop_events: Dict[str, asyncio.Event] = {}
_scrape_queues: Dict[str, deque] = {} # job_id -> deque of new emails for SSE
def _get_outreach_db():
global _outreach_db
if _outreach_db is not None:
return _outreach_db
try:
from pymongo import MongoClient
client = MongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=3000)
client.admin.command("ping")
_outreach_db = client[settings.mongodb_database]
return _outreach_db
except Exception as exc:
logger.error("Outreach MongoDB connection failed: %s", exc)
return None
# ── PAT Management ────────────────────────────────────────────────────────
class AddPATRequest(BaseModel):
token: str
label: str = ""
@router.post("/api/outreach/pats")
async def add_pat(req: AddPATRequest, user: dict = Depends(_verify_admin_token)):
db = _get_outreach_db()
if db is None:
raise HTTPException(status_code=503, detail="Database unavailable")
req.token = req.token.strip()
coll = db["outreach_pats"]
if coll.find_one({"token": req.token}):
raise HTTPException(status_code=400, detail="This PAT already exists")
remaining, reset_at = 5000, None
headers = {"Authorization": f"token {req.token}", "Accept": "application/vnd.github.v3+json"}
try:
resp = httpx.get("https://api.github.com/user", headers=headers, timeout=15)
if resp.status_code == 200:
user_info = resp.json()
logger.info("[outreach] PAT validated for GitHub user: %s", user_info.get("login"))
elif resp.status_code == 401:
raise HTTPException(status_code=400, detail=f"Invalid PAT — GitHub says: {resp.json().get('message', 'Bad credentials')}")
elif resp.status_code == 403:
raise HTTPException(status_code=400, detail="PAT forbidden — may be IP-restricted or missing scopes")
else:
raise HTTPException(status_code=400, detail=f"GitHub returned HTTP {resp.status_code} on /user check")
# Also test repo access to confirm the PAT can read public repos
test_resp = httpx.get(
"https://api.github.com/repos/torvalds/linux/stargazers?per_page=1",
headers=headers, timeout=15,
)
if test_resp.status_code == 401:
raise HTTPException(status_code=400, detail="PAT is valid for /user but fails on repo access. Use a Classic token with 'repo' scope, or a Fine-grained token with 'All repositories' read access.")
if test_resp.status_code == 403:
raise HTTPException(status_code=400, detail="PAT lacks permission to read repository stargazers. Ensure 'repo' scope (classic) or read access to public repos (fine-grained).")
rl_resp = httpx.get("https://api.github.com/rate_limit", headers=headers, timeout=10)
if rl_resp.status_code == 200: