Dashboard zeigt die letzten Anfragen — Dauer, Cache-Quelle, p95, Trefferquote
Die Zeilen aus dem Anfrage-Log lagen bisher nur in der Datei. Jetzt gibt es sie über den Steuerkanal (`requests.tail`, Standard 20, Deckel 200) und das Dashboard zeigt sie: Zeit, Modell, Ziel, Status, Millisekunden, Cache-Quelle, Tokens, Kosten — dazu p95 und Trefferquote, ausdrücklich nur über die angezeigten Zeilen gerechnet. Gelesen wird der letzte Block der Datei (256 KB), nicht die ganze: ein Ledger wächst, und das Dashboard fragt regelmäßig. Die erste, womöglich angeschnittene Zeile fällt weg; bei mehr Zeilen als gefragt bleiben die neuesten, nicht die ersten (Ringpuffer, geprüft mit 500 Zeilen und count 9999: n=200, erste m300, letzte m499). Auf n95 live: control-Socket beantwortet requests.tail, Dashboard zeigt vier echte Anfragen mit 714–751 ms, Karte "Letzte Anfragen" im HTML, app.js liest sie über /api/requests. Tests: control.py prüft requests.tail gegen ein vorbereitetes Ledger und den Deckel — 11 statt 9 Prüfungen. make test: PASS, 222 Prüfungen, 154 s.
This commit is contained in:
1 parent
114d1acad0
commit
b71bfb5a0a
9 files changed
+196
-6
No files matched your search
@@ -316,8 +316,11 @@ spend_log /var/lib/junction/spend.jsonl
|
||||
|
||||
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.
|
||||
total and its per-model split, and a "Letzte Anfragen" card with the last 25 lines of
|
||||
the request log — time, model, endpoint, status, milliseconds, cache source, tokens,
|
||||
cost — plus p95 latency and hit ratio *for those lines*, labelled as such rather than
|
||||
implied for the whole day. It asks over the control channel (`spend.get`,
|
||||
`requests.tail`), 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
|
||||
@@ -489,6 +492,7 @@ others still arrive. Nothing is invented to fill the gap.
|
||||
| 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 |
|
||||
| — | `{"cmd":"requests.tail","count":"25"}` — the last N lines of the request log (capped at 200, read from the end of the file) |
|
||||
| POST | `/admin/pause/<name>` | stop routing there |
|
||||
| POST | `/admin/resume/<name>` | clear pause + cooldown + offline |
|
||||
| POST | `/admin/flush/cache` | drop every cached response |
|
||||
@@ -624,7 +628,7 @@ sums exactly what the ledger wrote. A third check would have caught a real
|
||||
use-after-free: the status code must be read out of the cached head *before* the body is
|
||||
sent, because another thread may replace that entry while this one is still writing —
|
||||
the whole suite also runs green under AddressSanitizer.
|
||||
Pass = `PASS` (220 checks), including two that would have caught the two mistakes this
|
||||
Pass = `PASS` (222 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.
|
||||
|
||||
|
||||
@@ -305,6 +305,23 @@ static char *dispatch(const char *req, size_t n)
|
||||
return out;
|
||||
}
|
||||
|
||||
if (!strcmp(cmd, "requests.tail")) {
|
||||
char count[16] = "";
|
||||
size_t len = 0;
|
||||
json_str(req, n, "count", count, sizeof count);
|
||||
char *rq_str = OPS->requests ? OPS->requests(count, &len) : NULL;
|
||||
if (!rq_str)
|
||||
return strdup("{\"ok\":false,\"error\":\"no request log\"}\n");
|
||||
char *out = malloc(len + 32);
|
||||
if (!out) {
|
||||
free(rq_str);
|
||||
return strdup("{\"ok\":false,\"error\":\"out of memory\"}\n");
|
||||
}
|
||||
snprintf(out, len + 32, "{\"ok\":true,\"requests\":%.*s}\n", (int)len, rq_str);
|
||||
free(rq_str);
|
||||
return out;
|
||||
}
|
||||
|
||||
if (!strcmp(cmd, "config.get")) {
|
||||
size_t len = 0;
|
||||
char *txt = OPS->config_text(&len);
|
||||
|
||||
@@ -38,6 +38,8 @@ typedef struct {
|
||||
char *(*mcp_tools)(size_t *len);
|
||||
/* Kosten eines Monats ("YYYY-MM", "" = laufender) als JSON (malloc). */
|
||||
char *(*spend)(const char *month, size_t *len);
|
||||
/* Die letzten N Zeilen des Anfrage-Logs (malloc). */
|
||||
char *(*requests)(const char *count, size_t *len);
|
||||
/* Laufende Konfiguration als Text (malloc). */
|
||||
char *(*config_text)(size_t *len);
|
||||
/* Konfiguration aus Text übernehmen und speichern. */
|
||||
|
||||
@@ -20,6 +20,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);
|
||||
char *j_requests_json(const char *count, 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);
|
||||
@@ -125,6 +126,11 @@ static char *ops_spend(const char *month, size_t *len)
|
||||
return j_spend_json(month, len);
|
||||
}
|
||||
|
||||
static char *ops_requests(const char *count, size_t *len)
|
||||
{
|
||||
return j_requests_json(count, len);
|
||||
}
|
||||
|
||||
static char *ops_mcp_tools(size_t *len)
|
||||
{
|
||||
static char buf[1024 * 1024];
|
||||
@@ -217,6 +223,7 @@ static j_control_ops OPS = {
|
||||
.rule_delete = ops_rule_delete,
|
||||
.endpoint_pause = ops_endpoint_pause,
|
||||
.spend = ops_spend,
|
||||
.requests = ops_requests,
|
||||
.mcp_tools = ops_mcp_tools,
|
||||
.config_text = ops_config_text,
|
||||
.config_apply = ops_config_apply,
|
||||
|
||||
@@ -923,6 +923,90 @@ static char *build_spend(long year, long mon, size_t *len_out)
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Die letzten N Zeilen des Anfrage-Logs. Nicht die ganze Datei: ein Ledger kann groß
|
||||
* werden, und das Dashboard fragt alle zwei Sekunden. Gelesen wird deshalb nur der
|
||||
* letzte Block, und die erste (möglicherweise angeschnittene) Zeile fällt weg. */
|
||||
char *j_requests_json(const char *count, size_t *len_out)
|
||||
{
|
||||
*len_out = 0;
|
||||
if (!CFG.spend_log[0]) {
|
||||
static const char none[] = "{\"lines\":[],\"error\":\"no spend_log configured\"}";
|
||||
char *e = malloc(sizeof none);
|
||||
if (e) { memcpy(e, none, sizeof none); *len_out = sizeof none - 1; }
|
||||
return e;
|
||||
}
|
||||
int want = count && count[0] ? atoi(count) : 20;
|
||||
if (want <= 0) want = 20;
|
||||
if (want > 200) want = 200;
|
||||
|
||||
FILE *f = fopen(CFG.spend_log, "r");
|
||||
char *body = NULL;
|
||||
size_t blen = 0;
|
||||
if (f) {
|
||||
const long keep = 256 * 1024;
|
||||
if (fseek(f, 0, SEEK_END) == 0) {
|
||||
long size = ftell(f);
|
||||
long from = size > keep ? size - keep : 0;
|
||||
if (from > 0 && fseek(f, from, SEEK_SET) == 0) {
|
||||
/* den angeschnittenen Anfang verwerfen */
|
||||
int ch;
|
||||
while ((ch = fgetc(f)) != EOF && ch != '\n') { }
|
||||
} else {
|
||||
(void)fseek(f, 0, SEEK_SET);
|
||||
}
|
||||
blen = (size_t)(size - from > 0 ? size - from : 0);
|
||||
if (blen > 0) {
|
||||
body = malloc(blen + 1);
|
||||
if (body) {
|
||||
size_t got = fread(body, 1, blen, f);
|
||||
body[got] = '\0';
|
||||
blen = got;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
if (!body) {
|
||||
static const char empty[] = "{\"lines\":[]}";
|
||||
char *e = malloc(sizeof empty);
|
||||
if (e) { memcpy(e, empty, sizeof empty); *len_out = sizeof empty - 1; }
|
||||
return e;
|
||||
}
|
||||
|
||||
/* Alle Zeilen durchgehen und die letzten `want` behalten: der Block kann mehr
|
||||
* Zeilen enthalten als gefragt, und dann sind die alten nicht die interessanten. */
|
||||
char *starts[200];
|
||||
int nstarts = 0;
|
||||
char *p = body;
|
||||
while (*p) {
|
||||
char *nl = strchr(p, '\n');
|
||||
size_t linelen = nl ? (size_t)(nl - p) : strlen(p);
|
||||
if (linelen > 2 && p[0] == '{' && p[linelen - 1] == '}') {
|
||||
if (nstarts == want) {
|
||||
memmove(starts, starts + 1, sizeof starts[0] * (size_t)(want - 1));
|
||||
nstarts--;
|
||||
}
|
||||
starts[nstarts++] = p;
|
||||
/* Zeilenende markieren, damit die Ausgabe nicht über die Zeile hinausläuft */
|
||||
p[linelen] = '\0';
|
||||
}
|
||||
if (!nl) break;
|
||||
p = nl + 1;
|
||||
}
|
||||
|
||||
size_t cap = 64;
|
||||
for (int i = 0; i < nstarts; i++) cap += strlen(starts[i]) + 2;
|
||||
char *out = malloc(cap);
|
||||
if (!out) { free(body); *len_out = 0; return NULL; }
|
||||
size_t u = (size_t)snprintf(out, cap, "{\"lines\":[");
|
||||
for (int i = 0; i < nstarts; i++)
|
||||
u += (size_t)snprintf(out + u, cap - u, "%s%s", i ? "," : "", starts[i]);
|
||||
u += (size_t)snprintf(out + u, cap - u, "]}");
|
||||
free(body);
|
||||
*len_out = u;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* GET /spend[?month=YYYY-MM] — dieselbe Auskunft über HTTP. */
|
||||
static void spend_page(j_conn *c, const char *path)
|
||||
{
|
||||
|
||||
+14
-3
@@ -149,6 +149,17 @@ req for "*" pass a
|
||||
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]}")
|
||||
|
||||
# 0b. Die letzten Zeilen des Anfrage-Logs
|
||||
r = ctrl({"cmd": "requests.tail", "count": "5"})
|
||||
rq = r.get("requests") or {}
|
||||
lines = rq.get("lines") or []
|
||||
if not r.get("ok") or len(lines) != 1 or lines[0].get("vkey") != "cab":
|
||||
failures.append(f"requests.tail: {str(r)[:160]}")
|
||||
# der Deckel greift, ohne dass die Datei wächst
|
||||
r = ctrl({"cmd": "requests.tail", "count": "9999"})
|
||||
if len((r.get("requests") or {}).get("lines") or []) != 1:
|
||||
failures.append("requests.tail: Deckel/Anzahl stimmt nicht")
|
||||
|
||||
# 1. ping und status
|
||||
r = ctrl({"cmd": "ping"})
|
||||
if not r.get("ok"):
|
||||
@@ -266,9 +277,9 @@ req for "*" pass a
|
||||
print((proc.stderr.read() or b"").decode()[-1500:])
|
||||
sys.exit(1)
|
||||
|
||||
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")
|
||||
print("PASS: 11 Prüfungen — Monatsauskunft (spend.get), Anfrage-Log (requests.tail), "
|
||||
"ping/status, Regel sofort wirksam, Regel löschen, Endpunkt pausieren, "
|
||||
"Konfiguration lesen/schreiben, kaputte Konfiguration abgelehnt, TCP-Kanal")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -303,6 +303,46 @@ function renderRules(rules) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRequests() {
|
||||
const body = $('#t-req tbody');
|
||||
if (!body) return;
|
||||
try {
|
||||
const r = await fetch('/api/requests?count=25').then((x) => x.json());
|
||||
const lines = (r.ok && r.requests && r.requests.lines) || [];
|
||||
body.innerHTML = '';
|
||||
if (!lines.length) {
|
||||
const stats = $('#req-stats');
|
||||
if (stats) stats.textContent = (r.error || 'noch keine Anfragen im Log');
|
||||
return;
|
||||
}
|
||||
for (const l of lines) {
|
||||
const tr = document.createElement('tr');
|
||||
const when = l.ts ? new Date(l.ts * 1000).toLocaleTimeString() : '—';
|
||||
const bad = l.status && l.status >= 400;
|
||||
tr.innerHTML = `
|
||||
<td class="muted">${when}</td>
|
||||
<td>${escapeHtml(l.model || '—')}</td>
|
||||
<td class="muted">${escapeHtml(l.endpoint || '—')}</td>
|
||||
<td class="num">${bad ? '<span class="tag bad">' + l.status + '</span>' : (l.status || '—')}</td>
|
||||
<td class="num">${l.latency_ms ?? '—'}</td>
|
||||
<td>${escapeHtml(l.cache || '—')}</td>
|
||||
<td class="num">${fmt(l.tokens_in)}/${fmt(l.tokens_out)}</td>
|
||||
<td class="num">${(l.cost_usd || 0).toFixed(6)}</td>`;
|
||||
body.appendChild(tr);
|
||||
}
|
||||
/* p95 und Trefferquote über genau diese Zeilen — nicht über den Tag. */
|
||||
const ms = lines.map((l) => Number(l.latency_ms) || 0).sort((a, b) => a - b);
|
||||
const p95 = ms.length ? ms[Math.min(ms.length - 1, Math.ceil(ms.length * 0.95) - 1)] : 0;
|
||||
const hits = lines.filter((l) => ['hit', 'peer', 'joined'].includes(l.cache)).length;
|
||||
const stats = $('#req-stats');
|
||||
if (stats) stats.textContent =
|
||||
`${lines.length} Anfragen · p95 ${p95} ms · Trefferquote ${Math.round(hits / lines.length * 100)} %`;
|
||||
} catch (e) {
|
||||
const stats = $('#req-stats');
|
||||
if (stats) stats.textContent = 'keine Auskunft';
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
}
|
||||
@@ -322,6 +362,7 @@ async function refresh() {
|
||||
renderMcp((data.status && data.status.mcp) || [], data.tools || []);
|
||||
renderVkeys();
|
||||
loadSpend();
|
||||
loadRequests();
|
||||
} catch (e) {
|
||||
status = null;
|
||||
renderHeader();
|
||||
|
||||
@@ -83,6 +83,20 @@
|
||||
steht mit 0 — das heißt „kein Limit“, nicht „unbekannt“.</p>
|
||||
</section>
|
||||
|
||||
<section class="card wide">
|
||||
<h2>Letzte Anfragen <small id="req-stats"></small></h2>
|
||||
<table id="t-req">
|
||||
<thead><tr>
|
||||
<th>Zeit</th><th>Modell</th><th>Ziel</th><th class="num">Status</th>
|
||||
<th class="num">ms</th><th>Cache</th><th class="num">ein/aus</th><th class="num">$</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<p class="hint">Eine Zeile je bedienter Anfrage aus dem Anfrage-Log. <b>p95</b> und
|
||||
<b>Trefferquote</b> gelten für die angezeigten Zeilen, nicht für den ganzen Tag —
|
||||
was nicht im Log steht, wird hier nicht behauptet.</p>
|
||||
</section>
|
||||
|
||||
<section class="card wide">
|
||||
<h2>Regeln <small id="c-rules"></small></h2>
|
||||
<table id="t-rules">
|
||||
|
||||
@@ -269,6 +269,16 @@ const server = http.createServer(async (req, res) => {
|
||||
}));
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && url.pathname === '/api/requests') {
|
||||
/* Die letzten Zeilen des Anfrage-Logs, über den Steuerkanal: das Dashboard liest
|
||||
* keine Datei, die junction nicht auch selbst ausliefern würde. */
|
||||
const count = url.searchParams.get('count') || '25';
|
||||
const r = await ask({ cmd: 'requests.tail', count }).catch((f) => ({ ok: false, error: f.message }));
|
||||
return send(res, 200, JSON.stringify(r.ok
|
||||
? { ok: true, requests: r.requests }
|
||||
: { ok: false, error: r.error || 'keine Auskunft' }));
|
||||
}
|
||||
|
||||
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. */
|
||||
|
||||
Reference in new issue
Block a user