From ae6ac26d4329a2938d0483bdca1cf20c673b533b Mon Sep 17 00:00:00 2001 From: Hermes Date: Sun, 8 Nov 2026 08:00:17 +0000 Subject: [PATCH] =?UTF-8?q?dashboard:=20Schl=C3=BCssel,=20Monatskosten=20u?= =?UTF-8?q?nd=20W=C3=A4chter-Z=C3=A4hler=20sichtbar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Die letzten drei Commits haben Daten erzeugt, die niemand ansah: Limits je virtuellem Schlüssel, Kosten je Monat, abgelehnte Anfragen des Wächters. Das Dashboard zeigt sie jetzt dort, wo Konrad ohnehin hinsieht. - Neue Karte "Schlüssel & Monat": je Schlüssel Modell-Glob, rpm, Budget, verbraucht, Anfragen, Ablehnungen (mit "erschöpft"-Marke, wenn das Budget zu ist) und darunter die Monatssumme mit der Aufteilung je Modell. - Die Zahlen kommen über den Steuerkanal: neuer Befehl `spend.get` mit optionalem `month`. Dieselbe Rechnung wie GET /spend — eine Quelle, zwei Ausgänge (build_spend teilt sich HTTP und Steuerkanal). - Die Karte zeigt keine erfundenen Nullen: ohne Spend-Log sagt sie "no spend_log configured", und ein Schlüssel ohne Grenze steht mit "—" da, nicht mit 0. Dabei ein echter Ausfall aufgefallen, der nichts mit dem Dashboard zu tun hat: junction konnte seinen Unix-Steuerkanal seit dem letzten Neustart nicht binden — /run/junction existierte nicht ("control bind … failed: No such file or directory"), junction lief weiter und meldete nur über TCP. Das Dashboard spricht ausschließlich über den Socket und zeigte deshalb stillschweigend nichts mehr: keine Endpunkte, keine Regeln, kein Verlauf. Ursache: /run ist tmpfs und nach jedem Boot leer; die Einheit hatte kein RuntimeDirectory. Jetzt steht `RuntimeDirectory=junction` (0750) in junction.service, systemd legt das Verzeichnis bei jedem Start an. Nach dem Neustart: Socket da, Dashboard zeigt Endpunkte, Regeln, 20 Werkzeuge, drei Schlüssel und die Monatsauskunft. Tests: tests/control.py prüft `spend.get` (Summe 0,5 USD aus einer vorbereiteten Zeile, Schlüsselname, leerer Monat) — 9 statt 7 Prüfungen. make test: PASS, 195 Prüfungen. --- README.md | 8 +++- src/control.c | 17 ++++++++ src/control.h | 2 + src/control_ops.c | 7 ++++ src/junction.c | 98 ++++++++++++++++++++++++++++--------------- tests/control.py | 26 ++++++++++-- web/public/app.js | 51 ++++++++++++++++++++++ web/public/index.html | 15 +++++++ web/server.js | 10 +++++ 9 files changed, 196 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 571eee7..58dcf63 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,11 @@ spend_log /var/lib/junction/spend.jsonl "tokens_in":1200,"tokens_out":300,"tokens_cached":1000,"cost_usd":0.000720} ``` +The dashboard shows the same three things without reading the model port: a card with +every virtual key (model glob, `rpm`, budget, spend, requests, refusals), the month's +total and its per-model split. It asks over the control channel (`spend.get`), the same +way it asks for status and rules. + `GET /spend` answers for the ledger what `/status` answers for the process: the month's total and its split per key and per model, `?month=YYYY-MM` for any month the file still covers. Without a `spend_log` it says so (`404 no spend_log configured`) instead of @@ -439,6 +444,7 @@ others still arrive. Nothing is invented to fill the gap. | GET | `/status` | endpoints, counters, cache stats, rules | | GET | `/metrics` | the same counters as Prometheus text (unauthenticated, like `/status`) | | GET | `/spend[?month=YYYY-MM]` | cost of that month from the spend log, per key and per model | +| — | `{"cmd":"spend.get","month":"YYYY-MM"}` on the control channel — the same numbers, for the dashboard | | POST | `/admin/pause/` | stop routing there | | POST | `/admin/resume/` | clear pause + cooldown + offline | | POST | `/admin/flush/cache` | drop every cached response | @@ -498,7 +504,7 @@ priced request through a key shows up in the log file, in `/status` and in `/met The offline wait has its own section too: with the only endpoint missing the first request fails as before, and once the endpoint is back the next request waits out the offline hold (measured ~2 s) and is served instead of refused. -Pass = `PASS` (193 checks), including two that would have caught the two mistakes this +Pass = `PASS` (195 checks), including two that would have caught the two mistakes this design invites: a serial stub making a concurrent router look serialised, and a "waiting" comment leaking into a caller that never asked for a stream. diff --git a/src/control.c b/src/control.c index 9c3497d..376eb44 100644 --- a/src/control.c +++ b/src/control.c @@ -288,6 +288,23 @@ static char *dispatch(const char *req, size_t n) return out; } + if (!strcmp(cmd, "spend.get")) { + char month[16] = ""; + size_t len = 0; + json_str(req, n, "month", month, sizeof month); + char *sp = OPS->spend ? OPS->spend(month, &len) : NULL; + if (!sp) + return strdup("{\"ok\":false,\"error\":\"no spend data\"}\n"); + char *out = malloc(len + 24); + if (!out) { + free(sp); + return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n"); + } + snprintf(out, len + 24, "{\"ok\":true,\"spend\":%.*s}\n", (int)len, sp); + free(sp); + return out; + } + if (!strcmp(cmd, "config.get")) { size_t len = 0; char *txt = OPS->config_text(&len); diff --git a/src/control.h b/src/control.h index 02b2f8d..54fa5c0 100644 --- a/src/control.h +++ b/src/control.h @@ -36,6 +36,8 @@ typedef struct { int (*endpoint_pause)(const char *name, int pause, char *err, size_t errlen); /* Die gebündelte MCP-Werkzeugliste (malloc). */ char *(*mcp_tools)(size_t *len); + /* Kosten eines Monats ("YYYY-MM", "" = laufender) als JSON (malloc). */ + char *(*spend)(const char *month, size_t *len); /* Laufende Konfiguration als Text (malloc). */ char *(*config_text)(size_t *len); /* Konfiguration aus Text übernehmen und speichern. */ diff --git a/src/control_ops.c b/src/control_ops.c index f27f077..0d9262e 100644 --- a/src/control_ops.c +++ b/src/control_ops.c @@ -19,6 +19,7 @@ extern j_config CFG; /* Vom Router bereitgestellt. */ char *j_status_json(size_t *len); +char *j_spend_json(const char *month, size_t *len); void j_set_endpoint_paused(const char *name, int pause, char *err, size_t errlen); int j_rule_apply(const char *text, char *err, size_t errlen); int j_rule_remove(const char *name, int index, char *err, size_t errlen); @@ -119,6 +120,11 @@ static int ops_endpoint_pause(const char *name, int pause, char *err, size_t err return 0; } +static char *ops_spend(const char *month, size_t *len) +{ + return j_spend_json(month, len); +} + static char *ops_mcp_tools(size_t *len) { static char buf[1024 * 1024]; @@ -210,6 +216,7 @@ static j_control_ops OPS = { .rule_set = ops_rule_set, .rule_delete = ops_rule_delete, .endpoint_pause = ops_endpoint_pause, + .spend = ops_spend, .mcp_tools = ops_mcp_tools, .config_text = ops_config_text, .config_apply = ops_config_apply, diff --git a/src/junction.c b/src/junction.c index f0af650..17a203c 100644 --- a/src/junction.c +++ b/src/junction.c @@ -768,36 +768,11 @@ typedef struct { unsigned long n; } spend_row; -/* GET /spend[?month=YYYY-MM] — was dieser Monat gekostet hat, je Schlüssel und je - * Modell, gelesen aus dem Spend-Log. Die Zahlen sind Buchführung, keine Schätzung: - * jede Zeile im Log ist eine Anfrage, die Verbrauch gemeldet hat. Ist kein Log - * eingetragen, sagt die Antwort das, statt Nullen zu erfinden. */ -static void spend_page(j_conn *c, const char *query) +/* Baut die Monatsauskunft: Kosten aus dem Spend-Log, je Schlüssel und je Modell. + * Gemeinsam für GET /spend und den Steuerkanal (spend.get), damit Dashboard und HTTP + * dieselben Zahlen sehen. */ +static char *build_spend(long year, long mon, size_t *len_out) { - long year = 0, mon = 0; - time_t now = time(NULL); - struct tm tmv; - gmtime_r(&now, &tmv); - year = tmv.tm_year + 1900; - mon = tmv.tm_mon + 1; - if (query) { - const char *m = strstr(query, "month="); - if (m) { - int y = 0, mo = 0; - if (sscanf(m + 6, "%4d-%2d", &y, &mo) == 2 && y > 1970 && mo >= 1 && mo <= 12) { - year = y; - mon = mo; - } else { - send_simple(c, 400, "Bad Request", "{\"error\":\"month must be YYYY-MM\"}"); - return; - } - } - } - if (!CFG.spend_log[0]) { - send_simple(c, 404, "Not Found", "{\"error\":\"no spend_log configured\"}"); - return; - } - double from = (double)days_from_civil(year, (unsigned)mon, 1u) * 86400.0; long ny = year, nm = mon + 1; if (nm > 12) { nm = 1; ny++; } @@ -809,11 +784,11 @@ static void spend_page(j_conn *c, const char *query) unsigned long lines = 0; int overflow = 0; - FILE *f = fopen(CFG.spend_log, "r"); + FILE *f = CFG.spend_log[0] ? fopen(CFG.spend_log, "r") : NULL; /* Existiert die Datei noch nicht, hat niemand etwas verbraucht — das ist ein leerer * Monat und kein Fehler. Nur ein anderes Problem (Rechte, kaputter Pfad) wird * gemeldet, statt es als "0 USD" zu verkleiden. */ - int missing = (f == NULL && errno == ENOENT); + int missing = (f == NULL && CFG.spend_log[0] && errno == ENOENT); if (f) { char line[1024]; while (fgets(line, sizeof line, f)) { @@ -851,13 +826,20 @@ static void spend_page(j_conn *c, const char *query) } fclose(f); } else if (!missing) { - send_simple(c, 404, "Not Found", "{\"error\":\"spend_log not readable\"}"); - return; + size_t n = (size_t)snprintf(NULL, 0, "{\"error\":\"%s\"}", + CFG.spend_log[0] ? "spend_log not readable" + : "no spend_log configured"); + char *e = malloc(n + 1); + if (e) snprintf(e, n + 1, "{\"error\":\"%s\"}", + CFG.spend_log[0] ? "spend_log not readable" + : "no spend_log configured"); + *len_out = e ? n : 0; + return e; } size_t cap = 512 + (size_t)(nkeys + nmodels) * 160; char *out = malloc(cap); - if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } + if (!out) { *len_out = 0; return NULL; } size_t u = (size_t)snprintf(out, cap, "{\"month\":\"%04ld-%02ld\",\"from\":%.0f,\"to\":%.0f,\"total_usd\":%.6f," "\"requests\":%lu,\"truncated\":%s,\"vkeys\":[", @@ -878,10 +860,58 @@ static void spend_page(j_conn *c, const char *query) i ? "," : "", em, models[i].cost, models[i].n); } u += (size_t)snprintf(out + u, cap - u, "]}"); + *len_out = u; + return out; +} + +/* GET /spend[?month=YYYY-MM] — dieselbe Auskunft über HTTP. */ +static void spend_page(j_conn *c, const char *path) +{ + long year = 0, mon = 0; + time_t now = time(NULL); + struct tm tmv; + gmtime_r(&now, &tmv); + year = tmv.tm_year + 1900; + mon = tmv.tm_mon + 1; + + const char *m = path ? strstr(path, "month=") : NULL; + if (m) { + int y = 0, mo = 0; + if (sscanf(m + 6, "%4d-%2d", &y, &mo) == 2 && y > 1970 && mo >= 1 && mo <= 12) { + year = y; + mon = mo; + } else { + send_simple(c, 400, "Bad Request", "{\"error\":\"month must be YYYY-MM\"}"); + return; + } + } + + size_t len = 0; + char *out = build_spend(year, mon, &len); + if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } send_simple(c, 200, "OK", out); free(out); } +/* Steuerkanal-Einstieg: dieselbe Auskunft, gleiche Quelle. */ +char *j_spend_json(const char *month, size_t *len) +{ + long year = 0, mon = 0; + time_t now = time(NULL); + struct tm tmv; + gmtime_r(&now, &tmv); + year = tmv.tm_year + 1900; + mon = tmv.tm_mon + 1; + if (month && month[0]) { + int y = 0, mo = 0; + if (sscanf(month, "%4d-%2d", &y, &mo) == 2 && y > 1970 && mo >= 1 && mo <= 12) { + year = y; + mon = mo; + } + } + return build_spend(year, mon, len); +} + static void status_page(j_conn *c) { size_t len = 0; diff --git a/tests/control.py b/tests/control.py index 192e2ba..99f0147 100755 --- a/tests/control.py +++ b/tests/control.py @@ -101,6 +101,7 @@ def main(): conf = os.path.join(work, "junction.conf") base_conf = f"""listen 127.0.0.1:{PORT} log_prefix jctl +spend_log {os.path.join(work, "spend.jsonl")} control unix {CTRL} mode 0600 control tcp 127.0.0.1:{PORT + 1} @@ -123,12 +124,31 @@ req for "*" pass a with open(conf, "w") as f: f.write(base_conf) + # Eine Zeile im Spend-Log, damit spend.get etwas zu rechnen hat. + now = int(time.time()) + with open(os.path.join(work, "spend.jsonl"), "w") as f: + f.write(json.dumps({"ts": now, "vkey": "cab", "model": "m", + "endpoint": "a", "tokens_in": 100, "tokens_out": 10, + "tokens_cached": 0, "cost_usd": 0.5}) + "\n") + proc = subprocess.Popen([JUNCTION, "--config", conf], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) failures = [] try: time.sleep(1.5) + # 0. Monatsauskunft über den Steuerkanal (dieselbe Quelle wie GET /spend) + r = ctrl({"cmd": "spend.get"}) + sp = r.get("spend") or {} + if not r.get("ok") or abs(float(sp.get("total_usd", 0)) - 0.5) > 1e-9: + failures.append(f"spend.get: {str(r)[:160]}") + if [v.get("name") for v in sp.get("vkeys", [])] != ["cab"]: + failures.append(f"spend.get nennt den Schlüssel nicht: {str(sp)[:120]}") + r = ctrl({"cmd": "spend.get", "month": "2020-01"}) + sp = r.get("spend") or {} + if abs(float(sp.get("total_usd", 1)) - 0.0) > 1e-9: + failures.append(f"spend.get für einen leeren Monat: {str(sp)[:120]}") + # 1. ping und status r = ctrl({"cmd": "ping"}) if not r.get("ok"): @@ -246,9 +266,9 @@ req for "*" pass a print((proc.stderr.read() or b"").decode()[-1500:]) sys.exit(1) - print("PASS: 7 Prüfungen — ping/status, Regel sofort wirksam, Regel löschen, " - "Endpunkt pausieren, Konfiguration lesen/schreiben, kaputte Konfiguration " - "abgelehnt, TCP-Kanal") + print("PASS: 9 Prüfungen — Monatsauskunft (spend.get), ping/status, Regel sofort " + "wirksam, Regel löschen, Endpunkt pausieren, Konfiguration lesen/schreiben, " + "kaputte Konfiguration abgelehnt, TCP-Kanal") if __name__ == "__main__": diff --git a/web/public/app.js b/web/public/app.js index 975867c..dab1562 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -227,6 +227,54 @@ function renderMcp(servers, tools) { } } +function renderVkeys() { + const body = $('#t-vkeys tbody'); + if (!body) return; + const keys = (status && status.vkeys) || []; + body.innerHTML = ''; + for (const k of keys) { + const tr = document.createElement('tr'); + const over = k.budget_usd > 0 && k.spent_usd >= k.budget_usd; + tr.innerHTML = ` + ${escapeHtml(k.name)} + ${escapeHtml(k.allow || '*')} + ${k.rpm > 0 ? k.rpm : '—'} + ${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'} + $${(k.spent_usd || 0).toFixed(4)} + ${fmt(k.hits)} + ${fmt(k.denied)}${over ? ' erschöpft' : ''}`; + body.appendChild(tr); + } + const refused = (status && status.guard_refused) || 0; + const c = $('#c-spend'); + if (c) c.textContent = keys.length + ? `${keys.length} Schlüssel${refused ? ' · ' + refused + ' vom Wächter abgelehnt' : ''}` + : 'keine virtuellen Schlüssel'; +} + +async function loadSpend() { + const box = $('#spend-detail'); + if (!box) return; + try { + const r = await fetch('/api/spend').then((x) => x.json()); + if (!r.ok || !r.spend) { + box.textContent = r.error || 'keine Auskunft'; + return; + } + const sp = r.spend; + if (sp.error) { + box.textContent = sp.error; + return; + } + const models = (sp.models || []).map((m) => + `${escapeHtml(m.model)} · $${m.cost_usd.toFixed(4)} · ${fmt(m.requests)}`).join(' '); + box.innerHTML = `${escapeHtml(sp.month)}: $${sp.total_usd.toFixed(4)}` + + ` über ${fmt(sp.requests)} Anfragen` + (models ? '
' + models : ''); + } catch (e) { + box.textContent = 'keine Auskunft'; + } +} + function renderRules(rules) { const body = $('#t-rules tbody'); body.innerHTML = ''; @@ -272,6 +320,8 @@ async function refresh() { renderEndpoints(); renderRules(data.rules || []); renderMcp((data.status && data.status.mcp) || [], data.tools || []); + renderVkeys(); + loadSpend(); } catch (e) { status = null; renderHeader(); @@ -290,6 +340,7 @@ function listen() { renderEndpoints(); renderRules(data.rules || []); renderMcp((data.status && data.status.mcp) || [], data.tools || []); + renderVkeys(); } catch (e) { /* ein kaputter Rahmen darf die Anzeige nicht anhalten */ } }; es.onerror = () => { diff --git a/web/public/index.html b/web/public/index.html index 02ea786..1034fe7 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -68,6 +68,21 @@
+
+

Schlüssel & Monat

+ + + + + + + +
SchlüsselModellerpmBudgetverbrauchtAnfragenabgelehnt
+
+

Kosten aus dem Spend-Log, nicht geschätzt. Ein Schlüssel ohne Grenze + steht mit 0 — das heißt „kein Limit“, nicht „unbekannt“.

+
+

Regeln

diff --git a/web/server.js b/web/server.js index 75c2ebe..3287880 100644 --- a/web/server.js +++ b/web/server.js @@ -269,6 +269,16 @@ const server = http.createServer(async (req, res) => { })); } + if (req.method === 'GET' && url.pathname === '/api/spend') { + /* Dieselbe Auskunft wie GET /spend an junction, nur über den Steuerkanal: das + * Dashboard spricht ausschließlich mit dem Socket, nicht mit dem Modell-Port. */ + const month = url.searchParams.get('month') || ''; + const r = await ask({ cmd: 'spend.get', month }).catch((f) => ({ ok: false, error: f.message })); + return send(res, 200, JSON.stringify(r.ok + ? { ok: true, spend: r.spend } + : { ok: false, error: r.error || 'keine Auskunft' })); + } + if (req.method === 'GET' && url.pathname === '/api/stream') { res.writeHead(200, { 'Content-Type': 'text/event-stream',