latest changes
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
"""Server-side adapter for the local Codex usage service."""
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from django.core.cache import caches
|
||||
|
||||
|
||||
URL = os.environ.get("DASHBOARD_CODEX_USAGE_URL", "http://192.168.1.122:3100/api/usage")
|
||||
CACHE = caches["weather"]
|
||||
FRESH_SECONDS = 45
|
||||
STALE_SECONDS = 15 * 60
|
||||
|
||||
|
||||
def _percentage(value):
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
||||
return None
|
||||
return round(max(0, min(100, 100 - value)))
|
||||
|
||||
|
||||
def _time(value):
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
||||
return None
|
||||
try:
|
||||
return datetime.fromtimestamp(value, timezone.utc)
|
||||
except (ValueError, OverflowError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def _display(data):
|
||||
if not isinstance(data, dict) or data.get("service") != "codex":
|
||||
raise ValueError("Unexpected usage response")
|
||||
raw = data.get("raw")
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("Usage details unavailable")
|
||||
buckets = raw.get("rateLimitsByLimitId")
|
||||
if not isinstance(buckets, dict) or not buckets:
|
||||
buckets = {"codex": raw.get("rateLimits")}
|
||||
windows = []
|
||||
for name, bucket in list(buckets.items())[:10]:
|
||||
if not isinstance(bucket, dict):
|
||||
continue
|
||||
for key in ("primary", "secondary"):
|
||||
window = bucket.get(key)
|
||||
if not isinstance(window, dict):
|
||||
continue
|
||||
duration = window.get("windowDurationMins")
|
||||
title = {300: "5 hours", 10080: "Weekly"}.get(duration, f"{duration} min" if type(duration) is int and 0 < duration < 100000 else key.title())
|
||||
windows.append({
|
||||
"title": title,
|
||||
"remaining": _percentage(window.get("usedPercent")),
|
||||
"reset": _time(window.get("resetsAt")),
|
||||
"bucket": str(name)[:32],
|
||||
})
|
||||
checked = data.get("last_checked")
|
||||
try:
|
||||
checked = datetime.fromisoformat(checked.replace("Z", "+00:00")) if isinstance(checked, str) else None
|
||||
except ValueError:
|
||||
checked = None
|
||||
return {"windows": windows, "checked": checked, "stale": bool(data.get("stale") or data.get("status") != "ok"), "allowed": raw.get("ordinaryUsageAllowed") is True}
|
||||
|
||||
|
||||
def get_usage():
|
||||
cached = CACHE.get("codex-usage:v1")
|
||||
if cached and cached.get("fresh"):
|
||||
return cached["display"]
|
||||
try:
|
||||
request = urllib.request.Request(URL, headers={"Accept": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
body = response.read(1024 * 1024 + 1)
|
||||
if len(body) > 1024 * 1024:
|
||||
raise ValueError("Usage response too large")
|
||||
display = _display(json.loads(body))
|
||||
if display["stale"] and cached:
|
||||
raise ValueError("Usage service returned stale data")
|
||||
CACHE.set("codex-usage:v1", {"display": display, "fresh": True}, FRESH_SECONDS)
|
||||
CACHE.set("codex-usage:last-good", display, STALE_SECONDS)
|
||||
return display
|
||||
except (urllib.error.URLError, OSError, ValueError, TypeError, json.JSONDecodeError):
|
||||
previous = CACHE.get("codex-usage:last-good")
|
||||
return {**previous, "stale": True} if previous else None
|
||||
Reference in New Issue
Block a user