dashboard: Schlüssel, Monatskosten und Wächter-Zähler sichtbar

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.
This commit is contained in:
Hermes committed 2026-11-08 08:00:17 +00:00
1 parent 4cea332fd6
commit ae6ac26d43
9 files changed
+196 -38

No files matched your search

+7 -1
View File
@@ -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/<name>` | stop routing there |
| POST | `/admin/resume/<name>` | 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.
+17
View File
@@ -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);
+2
View File
@@ -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. */
+7
View File
@@ -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,
+64 -34
View File
@@ -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;
+23 -3
View File
@@ -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__":
+51
View File
@@ -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 = `
<td>${escapeHtml(k.name)}</td>
<td class="muted">${escapeHtml(k.allow || '*')}</td>
<td class="num">${k.rpm > 0 ? k.rpm : '—'}</td>
<td class="num">${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'}</td>
<td class="num">$${(k.spent_usd || 0).toFixed(4)}</td>
<td class="num">${fmt(k.hits)}</td>
<td class="num">${fmt(k.denied)}${over ? ' <span class="tag bad">erschöpft</span>' : ''}</td>`;
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) =>
`<span class="tool">${escapeHtml(m.model)} · $${m.cost_usd.toFixed(4)} · ${fmt(m.requests)}</span>`).join(' ');
box.innerHTML = `<b>${escapeHtml(sp.month)}</b>: $${sp.total_usd.toFixed(4)}`
+ ` über ${fmt(sp.requests)} Anfragen` + (models ? '<br>' + 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 = () => {
+15
View File
@@ -68,6 +68,21 @@
<div id="mcp-tools" class="tools"></div>
</section>
<section class="card wide">
<h2>Schlüssel &amp; Monat <small id="c-spend"></small></h2>
<table id="t-vkeys">
<thead><tr>
<th>Schlüssel</th><th>Modelle</th><th class="num">rpm</th>
<th class="num">Budget</th><th class="num">verbraucht</th>
<th class="num">Anfragen</th><th class="num">abgelehnt</th>
</tr></thead>
<tbody></tbody>
</table>
<div id="spend-detail" class="tools"></div>
<p class="hint">Kosten aus dem Spend-Log, nicht geschätzt. Ein Schlüssel ohne Grenze
steht mit 0 — das heißt „kein Limit“, nicht „unbekannt“.</p>
</section>
<section class="card wide">
<h2>Regeln <small id="c-rules"></small></h2>
<table id="t-rules">
+10
View File
@@ -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',