diff --git a/README.md b/README.md index 5eedfd0..571eee7 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,16 @@ spend_log /var/lib/junction/spend.jsonl "tokens_in":1200,"tokens_out":300,"tokens_cached":1000,"cost_usd":0.000720} ``` +`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 +returning zeros that look like a month without spending. + +Timestamps in the ledger are wall-clock (`time(NULL)`), not the monotonic clock the +timeouts use. That distinction cost a bug: with monotonic seconds the file said +`"ts":66841`, and after the next restart the month's spend was invisible — a budget that +forgets every restart is no budget. `/spend` is what made it visible. + At startup the keys' spent amounts are recomputed from that file for the current month. Without it a budget would be full again after every restart, which is the one thing a budget must not be. `/status` also keeps the in-memory numbers, so a request costs one @@ -428,6 +438,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 | | POST | `/admin/pause/` | stop routing there | | POST | `/admin/resume/` | clear pause + cooldown + offline | | POST | `/admin/flush/cache` | drop every cached response | @@ -478,14 +489,16 @@ a resource URI un-prefixed on `resources/read`, an unknown prefix refused, and a server not taking the list down. A guard script is tested from both sides: one that refuses a word it does not want (with its reason in the body and in `/metrics`), one that exits silently (the exit code becomes the reason), and a request that passes and is -logged as `guard_pass`. The key limits have their own +logged as `guard_pass`. `/spend` is checked against a seeded ledger: the month's total, +the split per key and model, a month with nothing in it, a malformed month, and a router +without a ledger saying exactly that. The key limits have their own file: a `rpm 1` key is served once and then refused with `429` and a `Retry-After`, a key whose budget the ledger already used up is refused before it routes anything, and a priced request through a key shows up in the log file, in `/status` and in `/metrics`. 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` (186 checks), including two that would have caught the two mistakes this +Pass = `PASS` (193 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/junction.c b/src/junction.c index dfae0cd..f0af650 100644 --- a/src/junction.c +++ b/src/junction.c @@ -566,7 +566,11 @@ static void spend_append(const char *vkey, const char *model, const char *ep, int n = snprintf(line, sizeof line, "{\"ts\":%.0f,\"vkey\":\"%s\",\"model\":\"%s\",\"endpoint\":\"%s\"," "\"tokens_in\":%ld,\"tokens_out\":%ld,\"tokens_cached\":%ld,\"cost_usd\":%.6f}\n", - now_s(), ev, em, ep ? ep : "", in, out, cached, cost); + /* Wanduhr, nicht now_s(): das ist monoton und taugt für Fristen, aber nicht + * für "welcher Monat war das". Mit der monotonen Zeit stand im Log "ts":66841, + * und beim nächsten Start war der Monatsverbrauch unsichtbar — ein Budget, das + * jeden Neustart vergisst, ist keins. */ + (double)time(NULL), ev, em, ep ? ep : "", in, out, cached, cost); if (n <= 0 || (size_t)n >= sizeof line) return; pthread_mutex_lock(&g_spend_mu); int fd = open(CFG.spend_log, O_WRONLY | O_CREAT | O_APPEND, 0600); @@ -743,6 +747,141 @@ static char *build_status(size_t *len_out) return out; } +/* Tage seit 1970-01-01 für ein Kalenderdatum, ohne timegm(): die Umrechnung ist + * arithmetisch, damit sie nicht von der Zeitzone des Prozesses abhängt. */ +static long days_from_civil(long y, unsigned m, unsigned d) +{ + y -= (m <= 2); + long era = (y >= 0 ? y : y - 399) / 400; + unsigned yoe = (unsigned)(y - era * 400); + unsigned doy = (153u * (m + (m > 2 ? -3u : 9u)) + 2u) / 5u + d - 1u; + unsigned doe = yoe * 365u + yoe / 4u - yoe / 100u + doy; + return era * 146097L + (long)doe - 719468L; +} + +#define SPEND_MAX_KEYS 32 +#define SPEND_MAX_MODELS 64 + +typedef struct { + char name[J_GLOB_MAX]; + double cost; + 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) +{ + 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++; } + double to = (double)days_from_civil(ny, (unsigned)nm, 1u) * 86400.0; + + spend_row keys[SPEND_MAX_KEYS], models[SPEND_MAX_MODELS]; + int nkeys = 0, nmodels = 0; + double total = 0.0; + unsigned long lines = 0; + int overflow = 0; + + FILE *f = fopen(CFG.spend_log, "r"); + /* 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); + if (f) { + char line[1024]; + while (fgets(line, sizeof line, f)) { + const char *ts = strstr(line, "\"ts\":"); + const char *cost = strstr(line, "\"cost_usd\":"); + char vk[J_GLOB_MAX] = "", md[J_GLOB_MAX] = ""; + if (!ts || !cost) continue; + double t = strtod(ts + 5, NULL); + if (t < from || t >= to) continue; + json_str_value(line, "vkey", vk, sizeof vk); + json_str_value(line, "model", md, sizeof md); + double cost_v = strtod(cost + 11, NULL); + total += cost_v; + lines++; + + int found = -1; + for (int i = 0; i < nkeys; i++) + if (!strcmp(keys[i].name, vk)) { found = i; break; } + if (found < 0 && nkeys < SPEND_MAX_KEYS) { + found = nkeys++; + snprintf(keys[found].name, sizeof keys[found].name, "%s", vk); + } + if (found >= 0) { keys[found].cost += cost_v; keys[found].n++; } + else overflow = 1; + + found = -1; + for (int i = 0; i < nmodels; i++) + if (!strcmp(models[i].name, md)) { found = i; break; } + if (found < 0 && nmodels < SPEND_MAX_MODELS) { + found = nmodels++; + snprintf(models[found].name, sizeof models[found].name, "%s", md); + } + if (found >= 0) { models[found].cost += cost_v; models[found].n++; } + else overflow = 1; + } + fclose(f); + } else if (!missing) { + send_simple(c, 404, "Not Found", "{\"error\":\"spend_log not readable\"}"); + return; + } + + 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; } + size_t u = (size_t)snprintf(out, cap, + "{\"month\":\"%04ld-%02ld\",\"from\":%.0f,\"to\":%.0f,\"total_usd\":%.6f," + "\"requests\":%lu,\"truncated\":%s,\"vkeys\":[", + year, mon, from, to, total, lines, overflow ? "true" : "false"); + for (int i = 0; i < nkeys; i++) { + char en[J_GLOB_MAX]; + json_escape(keys[i].name, en, sizeof en); + u += (size_t)snprintf(out + u, cap - u, + "%s{\"name\":\"%s\",\"cost_usd\":%.6f,\"requests\":%lu}", + i ? "," : "", en, keys[i].cost, keys[i].n); + } + u += (size_t)snprintf(out + u, cap - u, "],\"models\":["); + for (int i = 0; i < nmodels; i++) { + char em[J_GLOB_MAX]; + json_escape(models[i].name, em, sizeof em); + u += (size_t)snprintf(out + u, cap - u, + "%s{\"model\":\"%s\",\"cost_usd\":%.6f,\"requests\":%lu}", + i ? "," : "", em, models[i].cost, models[i].n); + } + u += (size_t)snprintf(out + u, cap - u, "]}"); + send_simple(c, 200, "OK", out); + free(out); +} + static void status_page(j_conn *c) { size_t len = 0; @@ -2442,6 +2581,7 @@ static void handle_client(j_conn *client) if (!strcmp(rq.path, "/status")) { status_page(client); goto done; } if (!strcmp(rq.path, "/metrics")) { metrics_page(client); goto done; } + if (!strncmp(rq.path, "/spend", 6)) { spend_page(client, rq.path); goto done; } if (!strncmp(rq.path, "/admin/", 7)) { admin(client, rq.path); goto done; } /* junction ist auch selbst ein MCP-Server: /mcp bündelt die Werkzeuge aller * eingetragenen Server. Vor der Modellvermittlung, weil hier kein Modell im diff --git a/tests/spend-vkey.sh b/tests/spend-vkey.sh index 6aba7f7..faec198 100644 --- a/tests/spend-vkey.sh +++ b/tests/spend-vkey.sh @@ -141,3 +141,20 @@ else bad "/metrics exports the spend per key" fi contains "$LM" 'junction_vkey_requests_total{vkey="hermes",outcome="ok"} 1' "/metrics counts the key's requests" + +# --- 4. Die Monatsauskunft -------------------------------------------------------------- +# Dieselbe Datei, ausgewertet: was hat dieser Monat gekostet, je Schlüssel und Modell. +SP=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend") +contains "$SP" '"total_usd":0.000720' "/spend sums the month's cost" +contains "$SP" '"name":"hermes","cost_usd":0.000720' "/spend names the key that spent it" +contains "$SP" '"model":"test/preis"' "/spend names the model" +contains "$SP" '"requests":1' "/spend counts the requests" +# Ein Monat davor darf nichts enthalten — sonst zählt das Fenster nicht. +PREV=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m 2>/dev/null || date -v-1m +%Y-%m) +SP0=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend?month=$PREV") +contains "$SP0" '"total_usd":0.000000' "/spend only counts the requested month" +SPBAD=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend?month=kapputt") +contains "$SPBAD" "month must be YYYY-MM" "a malformed month is refused" +# Ohne eingetragenes Log gibt es keine Zahlen — und keine erfundenen Nullen. +SPNONE=$(curl -s -m 5 "http://127.0.0.1:$P_RPM/spend") +contains "$SPNONE" "no spend_log configured" "/spend without a log says so instead of inventing zero"