diff --git a/README.md b/README.md index 368d41c..6053c02 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,17 @@ serves it — and what to do when none of them wants to. endpoint whose `context` is smaller than a *declared* budget is skipped; a request that declares nothing is passed through unsized. - **Failover with cooldown**, and a `503` that names why each endpoint was skipped. +- **A second attempt before failover.** `429`, `408` and `5xx` are retried on the *same* + endpoint (`retry_num`, `retry_backoff`), because such a state usually clears in + seconds while the next link in the chain costs money or context. Connect failures are + explicitly not retried — "unreachable" is offline, and waiting for that is the hooks' + job. A stream that has already started is never repeated. +- **Key pools per endpoint.** `api_key_env` may stand several times; each attempt takes + the next key, so a `429` on one account is answered by trying the next one instead of + giving up the endpoint. `/status` and `/metrics` show the pool size as `keys`. +- **Prometheus `/metrics`.** The same numbers as `/status`, in the text format a scraper + reads — `junction_endpoint_up{endpoint="…"}` is 1 unless the endpoint is paused, + offline, cooling down or over its hard budget. - **Concurrency with a queue.** One thread per connection, `max_inflight` upstream requests at a time, the rest wait in line instead of being refused. A waiting *streaming* caller is told why it waits — as SSE comments (`: junction: waiting for @@ -168,11 +179,55 @@ at all are asked again through their own API: `ollama.com` answers `/api/show` w both are silent does the endpoint's `context` key apply. Nothing in that chain is estimated, and `need` still reads only the budget the client declared. +## Retry, key pools, metrics + +A `429`, `408` or `5xx` is retried on the same endpoint before the chain moves on: + +```conf +retry_num 1 # additional attempts on the same endpoint (0 = never) +retry_backoff 0.5 # attempt n waits n × this many seconds +``` + +The reason is cost, not politeness: an overloaded cloud node usually recovers in +seconds, while the next link in the chain may be a paid one or one that cannot hold the +context. What is *not* retried: connect failures (that state is `offline`, and hooks +own it), any `4xx` other than the ones named, and anything after the stream head has +reached the client. `Retry-After` is not evaluated — the pause comes from +`retry_backoff` alone. + +A key pool is written by repeating `api_key_env`: + +```conf +endpoint cloud { + base https://api.example.com/v1 + api_key_env EXAMPLE_KEY_A + api_key_env EXAMPLE_KEY_B +} +``` + +Each attempt takes the next key, so two accounts are two quotas: a `429` on A is +answered with B, and only when every key has failed does the endpoint count as failed. + +`GET /metrics` serves the same numbers as `/status` in the Prometheus text format — +requests and retries, tokens, cost, cache, queue, compression, and per endpoint +`up`, requests, inflight, `last_ms`, offline/cooldown seconds, usage percent, pool size, +`paused` and cost. Like `/status` it is **not authenticated**. + +A scraper that does not run on this host does not need to reach the model port for that: + +```conf +metrics tcp 192.168.1.148:9180 +``` + +That listener answers `GET /metrics` and nothing else — `/v1` and `/admin` stay on +`listen`, so a monitoring container can read the numbers without also being able to +pause endpoints or rewrite the configuration. + ## Keys Global: `listen`, `connect_timeout_ms`, `offline_hold_s`, `max_body_bytes`, `log_prefix`, `cache_ttl`, `cache_entries`, `cache_bytes`, `max_inflight`, -`queue_timeout`. +`queue_timeout`, `retry_num`, `retry_backoff`, `metrics`. Endpoint: @@ -198,7 +253,7 @@ Endpoint: | `hook_retry` | how long to keep retrying hooks | | `hook_backoff` | sleep between hook attempts | | `wake` | command run once before the hook retries begin | -| `api_key_env` | env var sent as `Authorization: Bearer ...` | +| `api_key_env` | env var sent as `Authorization: Bearer ...` (repeatable: a pool, tried in turn) | | `tls_verify` | `on` (default) / `off` | | `tls_ca` | CA bundle for a private CA (default: system store) | | `cache` | `on` / `off` for this endpoint | @@ -262,6 +317,7 @@ others still arrive. Nothing is invented to fill the gap. | Method | Path | Effect | |---|---|---| | GET | `/status` | endpoints, counters, cache stats, rules | +| GET | `/metrics` | the same counters as Prometheus text (unauthenticated, like `/status`) | | POST | `/admin/pause/` | stop routing there | | POST | `/admin/resume/` | clear pause + cooldown + offline | | POST | `/admin/flush/cache` | drop every cached response | @@ -301,8 +357,12 @@ The suite also pins the two distinctions that are easy to get wrong: an image co only inside `messages` (a tool schema naming `image_url` and an escaped image part in a tool result both stay text, while a real image part still reaches the vision chain), and a limit published only in the endpoint's own API (`/api/show`) still beats the -number in the endpoint block. -Pass = `PASS` (130 checks), including two that would have caught the two mistakes this +number in the endpoint block. Three more cover the retry path: a `503` is retried on +the same endpoint and logged with the upstream status, a `429` on the first key of a +pool rotates to the second, and `/metrics` answers in the Prometheus text format with +`junction_endpoint_up` and the retry counter. The metrics listener is tested for the +opposite too: model traffic and `/admin` get a `404` there. +Pass = `PASS` (146 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/config.example b/config.example index c5d1250..5e0c5c4 100644 --- a/config.example +++ b/config.example @@ -15,8 +15,18 @@ max_body_bytes 67108864 max_inflight 4 queue_timeout 300 +# Retry before failover: 429/408/5xx are tried again on the SAME endpoint, because such +# a state usually clears in seconds while the next link may cost money or context. +# 0 disables it. retry_backoff is per attempt (attempt n waits n × this). +retry_num 1 +retry_backoff 0.5 + # Response cache (memory only). ttl 0 disables it. Only complete, non-streamed 200 # answers are stored, keyed on method + path + model + body. +# Only /metrics, only read-only. A Prometheus in a container or on another host can +# scrape the numbers here without reaching the model port (and /admin) at all. +# metrics tcp 192.168.1.148:9180 + cache_ttl 300 cache_entries 128 cache_bytes 33554432 @@ -71,6 +81,10 @@ endpoint cloud { idle_timeout 120 cache off # never store cloud answers api_key_env EXAMPLE_API_KEY + # Zweites Konto, zweites Kontingent: die Zeile darf mehrfach stehen. Jeder Versuch + # nimmt den nächsten Schlüssel, ein 429 auf dem ersten wird also mit dem zweiten + # beantwortet, statt den Endpunkt aufzugeben. + # api_key_env EXAMPLE_API_KEY_2 tls_verify on # off only for a self-signed internal endpoint # tls_ca /etc/junction/tls/internal-ca.pem header "X-Title: olivia" # static header sent with every request here diff --git a/examples/full-reference.conf b/examples/full-reference.conf index 4c0a058..2d5b480 100644 --- a/examples/full-reference.conf +++ b/examples/full-reference.conf @@ -54,6 +54,20 @@ max_inflight 8 # bekommt. Sekunden. Danach: Fehlerereignis, bei Streamern gefolgt von [DONE]. queue_timeout 300 +# Zweiter Versuch, bevor die Kette weiterzieht. 429/408/5xx sind oft in Sekunden +# vorbei; der nächste Link kostet dagegen Geld oder Kontext. Verbindungsfehler werden +# NICHT wiederholt (die heißen offline, dafür sind die Hooks da), und nach dem +# Streaming-Kopf wird nie wiederholt. Retry-After wird nicht ausgewertet. +retry_num 1 +retry_backoff 0.5 + +# ---------------------------------------------------------------- Überwachung +# +# Ein zweiter Listener, der ausschließlich GET /metrics beantwortet. Prometheus läuft +# hier im Container und kommt an das Loopback des Hosts nicht heran; statt /v1 und +# /admin ins Netz zu legen, gibt es genau diesen einen lesenden Port. +metrics tcp 192.168.1.148:9180 + # ---------------------------------------------------------------- Antwort-Cache # @@ -194,6 +208,10 @@ endpoint ollama1 { endpoint ollama2 { base https://ollama.com/v1 kind cloud + # Zwei Konten als zwei Endpunkte: so bleibt die Quote pro Konto sichtbar + # (usage_cmd 1 vs. 2). Als ein Endpunkt mit zwei api_key_env-Zeilen würde junction + # bei 429 auf das zweite Konto rotieren, aber usage_cmd und /api/show liefen nur + # mit dem ersten Schlüssel — die Quote des zweiten Kontos bliebe unsichtbar. context 128000 priority 50 timeout 900 diff --git a/src/config.c b/src/config.c index d4a8e3a..4bdd98b 100644 --- a/src/config.c +++ b/src/config.c @@ -78,6 +78,11 @@ void j_config_defaults(j_config *cfg) cfg->offline_hold_s = 20; cfg->max_inflight = 4; cfg->queue_timeout_s = 300; + /* Ein Wiederholungsversuch, eine halbe Sekunde Pause: genug für einen 429, der + * vom Anbieter nach Sekunden verfällt, und kurz genug, dass der Client es nicht + * als Hänger sieht. */ + cfg->retry_num = 1; + cfg->retry_backoff_s = 0.5; cfg->max_body_bytes = 64 * 1024 * 1024; cfg->cache_ttl_s = 0; cfg->cache_entries = 128; @@ -221,6 +226,8 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size } if (!strcmp(k, "connect_timeout_ms")) { if (n != 2 || as_double(w[1], &cfg->connect_timeout_ms)) goto bad; return 0; } if (!strcmp(k, "max_inflight")) { if (n != 2 || as_int(w[1], &cfg->max_inflight)) goto bad; return 0; } + if (!strcmp(k, "retry_num")) { if (n != 2 || as_int(w[1], &cfg->retry_num) || cfg->retry_num < 0) goto bad; return 0; } + if (!strcmp(k, "retry_backoff")) { if (n != 2 || as_double(w[1], &cfg->retry_backoff_s)) goto bad; return 0; } if (!strcmp(k, "queue_timeout")) { if (n != 2 || as_double(w[1], &cfg->queue_timeout_s)) goto bad; return 0; } if (!strcmp(k, "offline_hold_s")) { if (n != 2 || as_double(w[1], &cfg->offline_hold_s)) goto bad; return 0; } if (!strcmp(k, "max_body_bytes")) { if (n != 2 || as_int(w[1], &cfg->max_body_bytes)) goto bad; return 0; } @@ -234,6 +241,21 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size else goto bad; return 0; } + if (!strcmp(k, "metrics")) { + /* metrics tcp 192.168.1.148:9180 + * + * Nur /metrics, nur lesend. Der Modellpfad und der Steuerkanal bleiben, wo + * sie sind — ein Scraper im Container soll die Zahlen sehen, nicht die + * Schlüssel oder das Pausieren. */ + if (n != 3 || strcmp(w[1], "tcp")) goto bad; + const char *colon = strrchr(w[2], ':'); + if (!colon) goto bad; + snprintf(cfg->metrics_tcp_host, sizeof cfg->metrics_tcp_host, + "%.*s", (int)(colon - w[2]), w[2]); + cfg->metrics_tcp_port = atoi(colon + 1); + if (cfg->metrics_tcp_port <= 0 || cfg->metrics_tcp_port > 65535) goto bad; + return 0; + } if (!strcmp(k, "control")) { /* control unix /run/junction/control.sock [mode 0660] * control tcp 127.0.0.1:8091 @@ -382,7 +404,13 @@ static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, s snprintf(ep->base_cmd, sizeof ep->base_cmd, "%s", joined); return 0; } - if (!strcmp(k, "api_key_env")) { if (n != 2) goto bad; snprintf(ep->api_key_env, sizeof ep->api_key_env, "%s", w[1]); return 0; } + if (!strcmp(k, "api_key_env")) { + /* Mehrfach erlaubt: der Reihe nach, bei 429/401 auf den nächsten. */ + if (n != 2 || ep->key_env_count >= J_MAX_KEY_ENVS) goto bad; + snprintf(ep->api_key_env[ep->key_env_count], J_NAME_MAX, "%s", w[1]); + ep->key_env_count++; + return 0; + } if (!strcmp(k, "usage_cmd")) { /* Command mit Argumenten: Rest der Zeile zusammenfuegen, damit Quotes optional bleiben */ if (n < 2) goto bad; diff --git a/src/config.h b/src/config.h index 2a65fd7..bb66be8 100644 --- a/src/config.h +++ b/src/config.h @@ -47,6 +47,7 @@ #define J_MAX_EP_HEADERS 8 #define J_HDR_LINE_MAX 256 #define J_MAX_VKEYS 16 +#define J_MAX_KEY_ENVS 8 #define J_MAX_POOLS 16 #define J_MAX_MCP 16 @@ -109,7 +110,11 @@ typedef struct { char hooks[J_MAX_HOOKS][J_CMD_MAX]; int hook_count; char wake[J_CMD_MAX]; - char api_key_env[J_NAME_MAX]; + /* Schlüssel-Pool: api_key_env darf mehrfach stehen. Bei 429/401 rotiert junction + * auf den nächsten Schlüssel desselben Endpunkts, bevor es den Endpunkt aufgibt — + * zwei Konten bei einem Anbieter sind zwei Kontingente, nicht ein größeres. */ + char api_key_env[J_MAX_KEY_ENVS][J_NAME_MAX]; + int key_env_count; /* kind opencode: HTTP Basic, wie opencode serve ihn verlangt. Der Benutzer ist fest * "opencode", das Passwort steht in einer Datei und wird per Kommando gelesen, weil * der Dienst bei jedem Start ein neues erzeugt. */ @@ -155,6 +160,7 @@ typedef struct { double cost_usd; unsigned long cost_unknown; unsigned long fail_count; + unsigned long key_rr; /* welcher Schlüssel des Pools als nächster dran ist */ long last_ms; char last_error[256]; char last_hook_reason[256]; @@ -228,6 +234,11 @@ typedef struct { double offline_hold_s; int max_inflight; /* how many upstream requests may run at once */ double queue_timeout_s; /* how long a request may wait for a free slot */ + /* Wiederholung vor dem Weiterziehen: ein 429 oder 5xx desselben Endpunkts ist oft + * in Sekunden vorbei, ein Failover auf den nächsten Link kostet dagegen Geld oder + * Kontext. retry_num 0 schaltet es ab; dann gilt wieder "ein Fehler, nächster". */ + int retry_num; /* zusätzliche Versuche auf demselben Endpunkt */ + double retry_backoff_s; /* Wartezeit vor Versuch n = n * dieser Wert */ int max_body_bytes; char log_prefix[J_NAME_MAX]; @@ -280,6 +291,11 @@ typedef struct { int control_unix_mode; /* Dateirechte, Standard 0660 */ char control_tcp_host[J_NAME_MAX]; int control_tcp_port; + /* Eigener Listener, der ausschließlich GET /metrics beantwortet. So kann ein + * Prometheus im Container oder auf einem anderen Rechner scrapen, ohne dass + * /v1 und /admin dafür im Netz stehen müssen. 0 = kein solcher Listener. */ + char metrics_tcp_host[J_NAME_MAX]; + int metrics_tcp_port; char config_path[J_PATH_MAX]; /* woher die laufende Konfiguration kam */ } j_config; diff --git a/src/junction.c b/src/junction.c index 5176e92..2bb3d7c 100644 --- a/src/junction.c +++ b/src/junction.c @@ -26,6 +26,8 @@ void j_control_ops_install(void); #include #include #include +#include +#include #include #include #include @@ -464,16 +466,22 @@ static void slot_release(void) } /* ------------------------------------------------------------------ respond */ -static void send_simple(j_conn *c, int code, const char *reason, const char *body) +static void send_ct(j_conn *c, int code, const char *reason, const char *ctype, + const char *body, size_t len) { char hdr[512]; int n = snprintf(hdr, sizeof hdr, - "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\n" + "HTTP/1.1 %d %s\r\nContent-Type: %s\r\n" "Content-Length: %zu\r\nConnection: close\r\n\r\n", - code, reason, strlen(body)); + code, reason, ctype, len); char err[128]; if (j_conn_write(c, hdr, (size_t)n, err, sizeof err) < 0) return; - (void)j_conn_write(c, body, strlen(body), err, sizeof err); + if (len) (void)j_conn_write(c, body, len, err, sizeof err); +} + +static void send_simple(j_conn *c, int code, const char *reason, const char *body) +{ + send_ct(c, code, reason, "application/json", body, strlen(body)); } /* Verbrauch aus einer Antwort lesen: prompt_tokens, completion_tokens und, wenn der @@ -525,6 +533,12 @@ static unsigned long g_compress_reqs; static unsigned long g_compress_bytes_in; static unsigned long g_compress_bytes_out; +/* Wie oft ein Endpunkt ein zweites Mal gefragt wurde, statt weiterzuziehen. */ +static unsigned long g_retries; + +/* Eigener Listener nur für /metrics (siehe metrics_thread). */ +static char *build_metrics(size_t *len_out); + /* Baut den Statusbericht. Wird von /status und vom Steuerkanal benutzt, damit * Dashboard und HTTP dieselben Zahlen sehen — zwei Quellen wären zwei Wahrheiten. */ static char *build_status(size_t *len_out) @@ -552,7 +566,7 @@ static char *build_status(size_t *len_out) "\"last_ms\":%ld,\"offline_s\":%d,\"cooldown_s\":%d," "\"usage_percent\":%.2f,\"usage_used_usd\":%.2f,\"usage_budget_usd\":%.2f," "\"usage_ok\":%d,\"exhausted\":%d,\"budget_soft\":%.0f,\"budget_hard\":%.0f," - "\"offpeak\":%d,\"cost\":%.2f,\"hooks\":%d," + "\"offpeak\":%d,\"cost\":%.2f,\"hooks\":%d,\"keys\":%d," "\"wakeable\":%s,\"tls\":%s,\"cache\":%d,\"vision\":%d,\"compress\":%d," "\"last_error\":\"%s\",\"last_hook_reason\":\"%s\"}", i ? "," : "", ep->name, ep->base, ep->kind, ep->context, ep->priority, @@ -563,7 +577,7 @@ static char *build_status(size_t *len_out) ep->usage_percent, ep->usage_used_usd, ep->usage_budget_usd, ep->usage_ok, ep->exhausted, ep->budget_soft, ep->budget_hard, ep->offpeak_active ? 1 : 0, ep->cost_weight, - ep->hook_count, ep->wake[0] ? "true" : "false", + ep->hook_count, ep->key_env_count, ep->wake[0] ? "true" : "false", !strncmp(ep->base, "https://", 8) ? "true" : "false", ep->cache_on, ep->vision, (ep->compress >= 0) ? ep->compress : (CFG.compress != J_COMPRESS_OFF), errs, hook); @@ -621,10 +635,12 @@ static char *build_status(size_t *len_out) } used += (size_t)snprintf(out + used, cap - used, "\"requests\":{\"ok\":%lu,\"fail\":%lu}," + "\"retries\":{\"count\":%lu,\"num\":%d,\"backoff_s\":%.2f}," "\"traffic\":{\"request_bytes\":%lu,\"response_bytes\":%lu}," "\"latency\":{\"avg_ms\":%.1f,\"samples\":%lu}," "\"uptime_s\":%.0f}", - g_req_ok, g_req_fail, g_req_bytes, g_resp_bytes, + g_req_ok, g_req_fail, g_retries, CFG.retry_num, CFG.retry_backoff_s, + g_req_bytes, g_resp_bytes, g_latency_n ? g_latency_ms_sum / (double)g_latency_n : -1.0, g_latency_n, t - g_started_at); *len_out = used; @@ -640,6 +656,229 @@ static void status_page(j_conn *c) free(out); } +/* --------------------------------------------------------------- Prometheus */ + +static void met(char *out, size_t cap, size_t *used, const char *fmt, ...) +{ + if (*used >= cap) return; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(out + *used, cap - *used, fmt, ap); + va_end(ap); + if (n > 0) *used += (size_t)n; +} + +/* Prometheus-Textformat. Dieselben Zahlen wie /status, nur in der Form, die ein + * Scraper lesen kann: die Überwachung soll nicht selbst JSON nach Prometheus + * übersetzen müssen, und zwei Quellen wären zwei Wahrheiten. */ +static char *build_metrics(size_t *len_out) +{ + double t = now_s(); + size_t entries = 0, bytes = 0; + unsigned long hits = 0, misses = 0; + j_cache_stats(&entries, &bytes, &hits, &misses); + pthread_mutex_lock(&SLOTS.mu); + int inflight = SLOTS.inflight, waiting = SLOTS.waiting; + pthread_mutex_unlock(&SLOTS.mu); + + size_t cap = 8192 + (size_t)CFG.endpoint_count * 1600; + char *out = malloc(cap); + if (!out) { *len_out = 0; return NULL; } + size_t u = 0; + + met(out, cap, &u, + "# HELP junction_requests_total Requests by outcome.\n" + "# TYPE junction_requests_total counter\n" + "junction_requests_total{outcome=\"ok\"} %lu\n" + "junction_requests_total{outcome=\"fail\"} %lu\n" + "# HELP junction_retries_total Second attempts on the same endpoint before failover.\n" + "# TYPE junction_retries_total counter\n" + "junction_retries_total %lu\n" + "# HELP junction_tokens_total Tokens reported by the upstream, by direction.\n" + "# TYPE junction_tokens_total counter\n" + "junction_tokens_total{direction=\"in\"} %lu\n" + "junction_tokens_total{direction=\"out\"} %lu\n" + "junction_tokens_total{direction=\"cached\"} %lu\n" + "# HELP junction_cost_usd_total Cost of served requests, from the price table.\n" + "# TYPE junction_cost_usd_total counter\n" + "junction_cost_usd_total %.6f\n" + "junction_cost_unknown_total %lu\n" + "# TYPE junction_latency_ms gauge\n" + "junction_latency_ms_avg %.1f\n" + "junction_latency_samples %lu\n" + "# TYPE junction_cache_entries gauge\n" + "junction_cache_entries %zu\n" + "# TYPE junction_cache_bytes gauge\n" + "junction_cache_bytes %zu\n" + "# TYPE junction_cache_hits_total counter\n" + "junction_cache_hits_total %lu\n" + "# TYPE junction_cache_misses_total counter\n" + "junction_cache_misses_total %lu\n" + "# TYPE junction_cache_joined_total counter\n" + "junction_cache_joined_total %lu\n" + "# TYPE junction_inflight gauge\n" + "junction_inflight %d\n" + "# TYPE junction_waiting gauge\n" + "junction_waiting %d\n" + "# TYPE junction_max_inflight gauge\n" + "junction_max_inflight %d\n" + "# HELP junction_compress_bytes_total Tool output removed before the model saw it.\n" + "# TYPE junction_compress_bytes_total counter\n" + "junction_compress_requests_total %lu\n" + "junction_compress_bytes_total{direction=\"in\"} %lu\n" + "junction_compress_bytes_total{direction=\"out\"} %lu\n" + "# TYPE junction_uptime_seconds gauge\n" + "junction_uptime_seconds %.0f\n" + "# TYPE junction_request_bytes_total counter\n" + "junction_request_bytes_total %lu\n" + "junction_response_bytes_total %lu\n", + g_req_ok, g_req_fail, g_retries, + g_tokens_in, g_tokens_out, g_tokens_cached, + g_cost_usd, g_cost_unknown, + g_latency_n ? g_latency_ms_sum / (double)g_latency_n : -1.0, g_latency_n, + entries, bytes, hits, misses, j_cache_flight_joined(), + inflight, waiting, CFG.max_inflight, + g_compress_reqs, g_compress_bytes_in, g_compress_bytes_out, + t - g_started_at, g_req_bytes, g_resp_bytes); + + /* Pro Endpunkt: erreichbar, bedient, wie schnell, wie voll. "up" ist 1, solange + * nichts den Endpunkt ausschließt — pausiert, offline, im Cooldown oder über dem + * harten Budget heißt 0. Genau das fragt ein Alert ab. */ + met(out, cap, &u, + "# HELP junction_endpoint_up 1 unless the endpoint is paused, offline, cooling or over budget.\n" + "# TYPE junction_endpoint_up gauge\n" + "# HELP junction_endpoint_requests_total Requests this endpoint served or failed.\n" + "# TYPE junction_endpoint_requests_total counter\n" + "# HELP junction_endpoint_inflight gauge\n" + "# TYPE junction_endpoint_inflight gauge\n" + "# HELP junction_endpoint_last_ms gauge\n" + "# TYPE junction_endpoint_last_ms gauge\n" + "# HELP junction_endpoint_offline_seconds gauge\n" + "# TYPE junction_endpoint_offline_seconds gauge\n" + "# HELP junction_endpoint_cooldown_seconds gauge\n" + "# TYPE junction_endpoint_cooldown_seconds gauge\n" + "# HELP junction_endpoint_usage_percent gauge\n" + "# TYPE junction_endpoint_usage_percent gauge\n" + "# HELP junction_endpoint_keys gauge Number of API keys in the pool.\n" + "# TYPE junction_endpoint_keys gauge\n" + "# HELP junction_endpoint_cost_usd_total Cost this endpoint reported.\n" + "# TYPE junction_endpoint_cost_usd_total counter\n"); + for (int i = 0; i < CFG.endpoint_count; i++) { + j_endpoint *ep = &CFG.endpoints[i]; + STATE_LOCK(); + int offline_s = (int)(ep->offline_until > t ? ep->offline_until - t : 0); + int cooling_s = (int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0); + int over_budget = (ep->budget_hard > 0 && ep->usage_ok && + ep->usage_percent >= ep->budget_hard) || (ep->exhausted && ep->on_hard_skip); + int up = !(ep->paused || offline_s > 0 || cooling_s > 0 || over_budget); + met(out, cap, &u, + "junction_endpoint_up{endpoint=\"%s\"} %d\n" + "junction_endpoint_requests_total{endpoint=\"%s\",outcome=\"ok\"} %lu\n" + "junction_endpoint_requests_total{endpoint=\"%s\",outcome=\"fail\"} %lu\n" + "junction_endpoint_inflight{endpoint=\"%s\"} %d\n" + "junction_endpoint_last_ms{endpoint=\"%s\"} %ld\n" + "junction_endpoint_offline_seconds{endpoint=\"%s\"} %d\n" + "junction_endpoint_cooldown_seconds{endpoint=\"%s\"} %d\n" + "junction_endpoint_usage_percent{endpoint=\"%s\"} %.2f\n" + "junction_endpoint_keys{endpoint=\"%s\"} %d\n" + "junction_endpoint_paused{endpoint=\"%s\"} %d\n" + "junction_endpoint_cost_usd_total{endpoint=\"%s\"} %.6f\n", + ep->name, up, + ep->name, ep->ok_count, + ep->name, ep->fail_count, + ep->name, ep->inflight, + ep->name, ep->last_ms, + ep->name, offline_s, + ep->name, cooling_s, + ep->name, ep->usage_percent, + ep->name, ep->key_env_count, + ep->name, ep->paused ? 1 : 0, + ep->name, ep->cost_usd); + STATE_UNLOCK(); + } + + *len_out = u; + return out; +} + +static void metrics_page(j_conn *c) +{ + size_t len = 0; + char *out = build_metrics(&len); + if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } + send_ct(c, 200, "OK", "text/plain; version=0.0.4; charset=utf-8", out, len); + free(out); +} + +/* Ein zweiter, absichtlich kleiner Listener für die Überwachung: hier gibt es nur + * GET /metrics. /v1 und /admin bleiben auf dem Loopback-Listener. Ein Scraper + * braucht keine Schreibrechte, und er soll sie über das Netz auch nicht bekommen — + * deshalb kein Port-Sharing, sondern ein eigener, der nur diese eine Antwort kennt. */ +static void *metrics_conn(void *arg) +{ + int fd = (int)(long)arg; + j_conn c = J_CONN_INIT; + c.fd = fd; + c.role = "metrics"; + char req[2048], err[128]; + ssize_t n = j_conn_read(&c, req, sizeof req - 1, err, sizeof err); + if (n > 0) { + req[n] = '\0'; + if (!strncmp(req, "GET /metrics", 12)) { + size_t len = 0; + char *out = build_metrics(&len); + if (out) { + send_ct(&c, 200, "OK", "text/plain; version=0.0.4; charset=utf-8", out, len); + free(out); + } else { + send_simple(&c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); + } + } else { + send_simple(&c, 404, "Not Found", "{\"error\":\"metrics_only\"}"); + } + } + j_conn_close(&c); + return NULL; +} + +static void *metrics_thread(void *arg) +{ + (void)arg; + struct sockaddr_in addr; + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { jlog("metrics", "socket failed: %s", strerror(errno)); return NULL; } + int one = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); + memset(&addr, 0, sizeof addr); + addr.sin_family = AF_INET; + addr.sin_port = htons((uint16_t)CFG.metrics_tcp_port); + if (inet_pton(AF_INET, CFG.metrics_tcp_host, &addr.sin_addr) != 1) + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (bind(fd, (struct sockaddr *)&addr, sizeof addr) != 0 || listen(fd, 32) != 0) { + jlog("metrics", "tcp %s:%d failed: %s", CFG.metrics_tcp_host, + CFG.metrics_tcp_port, strerror(errno)); + close(fd); + return NULL; + } + jlog("metrics", "listening tcp %s:%d", CFG.metrics_tcp_host, CFG.metrics_tcp_port); + for (;;) { + int cfd = accept(fd, NULL, NULL); + if (cfd < 0) { + if (errno == EINTR) continue; + jlog("metrics", "accept failed: %s", strerror(errno)); + break; + } + pthread_t th; + pthread_attr_t at; + pthread_attr_init(&at); + pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED); + pthread_attr_setstacksize(&at, 128 * 1024); + if (pthread_create(&th, &at, metrics_conn, (void *)(long)cfd) != 0) close(cfd); + pthread_attr_destroy(&at); + } + close(fd); + return NULL; +} /* Übernimmt eine geprüfte Konfiguration. Endpunkte, Regeln und Werkzeugserver * werden unter Schreibsperre getauscht, damit kein Anfragepfad halb umgestellt @@ -660,6 +899,8 @@ void j_config_swap(j_config *fresh) CFG.pool_count = fresh->pool_count; memcpy(CFG.pools, fresh->pools, sizeof CFG.pools); CFG.balance = fresh->balance; + CFG.retry_num = fresh->retry_num; + CFG.retry_backoff_s = fresh->retry_backoff_s; CFG.compress = fresh->compress; CFG.compress_keep = fresh->compress_keep; CFG.compress_min_bytes = fresh->compress_min_bytes; @@ -1537,8 +1778,15 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, * the client's header must be dropped, or the upstream receives two Authorization * headers. Ollama shrugged; Cloudflare answers 400 Bad Request for it, which looks * like a broken endpoint and is really a duplicated header. */ - const char *inj_key = ep->api_key_env[0] ? getenv(ep->api_key_env) : NULL; - int inject_auth = (inj_key && inj_key[0]); + const char *inj_key = NULL; + if (ep->key_env_count > 0) { + STATE_LOCK(); + int ki = (int)(ep->key_rr++ % (unsigned long)ep->key_env_count); + STATE_UNLOCK(); + const char *v = getenv(ep->api_key_env[ki]); + if (v && v[0]) inj_key = v; + } + int inject_auth = (inj_key != NULL); for (int i = 0; i < rq->hdrs.n; i++) { const char *name = rq->hdrs.it[i].name; if (j_is_hop_by_hop(&rq->hdrs, name)) continue; @@ -1799,6 +2047,53 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, return 0; } +/* Ein Fehler, der einen zweiten Versuch auf demselben Endpunkt rechtfertigt: 429 + * (Kontingent gerade erschöpft, oft in Sekunden wieder frei) und 408/5xx (der Anbieter + * stolpert). Verbindungsfehler gehören ausdrücklich NICHT dazu — "nicht erreichbar" + * heißt offline, und darauf zu warten ist Aufgabe der Hooks, nicht eines Retrys. */ +static int err_retryable(const char *err) +{ + if (strncmp(err, "upstream_status_", 16)) return 0; + long code = strtol(err + 16, NULL, 10); + return code == 408 || code == 429 || code >= 500; +} + +/* Versucht denselben Endpunkt erneut, bevor die Kette weiterzieht. Jeder Versuch nimmt + * den nächsten Schlüssel aus dem Pool (key_rr dreht in forward_step weiter), also + * probiert der zweite Versuch bei zwei Konten das zweite Konto. Ist die Antwort schon + * beim Client (head_sent), wird nicht wiederholt: ein zweiter Rumpf käme zu spät. */ +static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, + const char *body, size_t len, const char *as_model, + const char *rq_model, const char *cache_state, + double started, int head_sent, char *err, size_t errlen) +{ + int tries = CFG.retry_num > 0 ? CFG.retry_num : 0; + /* Ein Schlüssel mehr im Pool ist ein Versuch mehr: sonst käme das zweite Konto + * nie zum Zug, wenn retry_num 0 ist. */ + if (ep->key_env_count - 1 > tries) tries = ep->key_env_count - 1; + + int rc = 0; + for (int a = 0; a <= tries; a++) { + if (a > 0) { + if (head_sent) return rc; + double nap_s = CFG.retry_backoff_s * (double)a; + jlog("retry", "endpoint=%s attempt=%d keys=%d backoff_ms=%.0f reason=%s", + ep->name, a + 1, ep->key_env_count, nap_s * 1000.0, err); + if (nap_s > 0) { + struct timespec ts = { (time_t)nap_s, + (time_t)((nap_s - (double)(time_t)nap_s) * 1e9) }; + nanosleep(&ts, NULL); + } + g_retries++; + } + rc = forward_step(client, ep, rq, body, len, as_model, rq_model, cache_state, + started, head_sent, err, errlen); + if (rc == 0 || rc == -2) return rc; + if (!err_retryable(err)) return rc; + } + return rc; +} + /* --------------------------------------------------------------- connection */ static int request_is_cacheable(const j_req *rq, char *why, size_t whylen) { @@ -1881,6 +2176,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, "/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 @@ -2161,8 +2457,8 @@ static void handle_client(j_conn *client) g_compress_bytes_in += cstat.bytes_in; g_compress_bytes_out += cstat.bytes_out; } - int rc = forward_step(client, ep, &rq, send_body, send_len, rule->target_as[t], model, - may_cache ? "miss" : "off", started, head_sent, err, sizeof err); + int rc = forward_with_retry(client, ep, &rq, send_body, send_len, rule->target_as[t], model, + may_cache ? "miss" : "off", started, head_sent, err, sizeof err); STATE_LOCK(); ep->inflight--; if (rc == 0) { @@ -2385,6 +2681,14 @@ int main(int argc, char **argv) return 1; } j_control_ops_install(); + /* Der Metrik-Listener ist optional und lebt nur, wenn die Konfiguration einen + * Port nennt. Scheitert er, läuft der Router weiter — Überwachung ist wichtig, + * aber nicht wichtiger als die Vermittlung selbst. */ + if (CFG.metrics_tcp_port > 0) { + pthread_t th; + if (pthread_create(&th, NULL, metrics_thread, NULL) == 0) + pthread_detach(th); + } jlog("listening", "addr=%s:%d endpoints=%d rules=%d tls=%d cache_ttl=%.0f", CFG.listen_host, CFG.listen_port, CFG.endpoint_count, CFG.rule_count, CFG.listen_tls, CFG.cache_ttl_s); diff --git a/src/models.c b/src/models.c index 7455d22..f82d5ed 100644 --- a/src/models.c +++ b/src/models.c @@ -179,7 +179,7 @@ static long publish_context_length(const char *root, const char *model, { char cmd[J_MODELS_CMD]; int off = snprintf(cmd, sizeof cmd, "curl -sS -m 6 -X POST "); - const char *key = ep->api_key_env[0] ? getenv(ep->api_key_env) : NULL; + const char *key = ep->key_env_count > 0 ? getenv(ep->api_key_env[0]) : NULL; if (key && *key) off += snprintf(cmd + off, sizeof cmd - (size_t)off, "-H 'Authorization: Bearer %s' ", key); @@ -220,7 +220,7 @@ static int fetch_json(const j_endpoint *ep, char **out, size_t *out_len) char cmd[J_MODELS_CMD]; int off = snprintf(cmd, sizeof cmd, "curl -sS -m 8 "); - const char *key = ep->api_key_env[0] ? getenv(ep->api_key_env) : NULL; + const char *key = ep->key_env_count > 0 ? getenv(ep->api_key_env[0]) : NULL; if (key && *key) { off += snprintf(cmd + off, sizeof cmd - (size_t)off, "-H 'Authorization: Bearer %s' ", key); diff --git a/tests/retry-metrics.sh b/tests/retry-metrics.sh new file mode 100644 index 0000000..623e2e3 --- /dev/null +++ b/tests/retry-metrics.sh @@ -0,0 +1,98 @@ +# Retry vor Failover, Schlüssel-Pool, /metrics — sourced von tests/run.sh. +# Erwartet PORT, TMP, PIDS, contains, log_has, ok, bad aus run.sh. + +echo "== 25. Wiederholung vor dem Weiterziehen ==" +# Ein Endpunkt, der die erste Anfrage mit 503 abweist und danach bedient. Ohne Retry +# müsste junction weiterziehen (und die Kette hätte kein zweites Ziel) — die Anfrage +# wäre also verloren, obwohl der Endpunkt eine Sekunde später gesund ist. +P_RETRY=$((PORT+30)) +P_RETRYJ=$((PORT+40)) +P_MET=$((PORT+37)) +STUB_STATE="$TMP/retry.state" tests/stub $P_RETRY "RETRY" --fail-n 1 & PIDS+=($!) +: > "$TMP/retry.state" +sleep 0.4 +cat > "$TMP/retry.conf" < "$TMP/retry.log" 2>&1 & PIDS+=($!) +sleep 0.5 +R=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$P_RETRYJ/v1/chat/completions") +contains "$R" "served by RETRY" "a 503 is retried on the same endpoint instead of failing over" +log_has "$TMP/retry.log" "retry endpoint=box" "the retry is logged with its reason" +log_has "$TMP/retry.log" "reason=upstream_status_503" "the log names the upstream status" +M=$(curl -s -m 10 "http://127.0.0.1:$P_RETRYJ/metrics") +contains "$M" "junction_retries_total 1" "the retry counter is exported" +contains "$M" "junction_requests_total{outcome=\"ok\"} 1" "the served request is counted" +S=$(curl -s -m 10 "http://127.0.0.1:$P_RETRYJ/status") +contains "$S" '"retries":{"count":1' "/status reports the retry count too" + +echo "== 26. Schlüssel-Pool pro Endpunkt ==" +# Zwei Konten bei einem Anbieter: der erste Schlüssel ist gesperrt (429), der zweite +# nicht. junction muss auf den zweiten rotieren, statt den Endpunkt aufzugeben. +P_POOL=$((PORT+35)) +P_POOLJ=$((PORT+36)) +P_KEY_FIRST=first-key-aaa +P_KEY_SECOND=second-key-bbb +tests/stub $P_POOL "POOL" --deny-auth "first-key" & PIDS+=($!) +sleep 0.4 +cat > "$TMP/pool.conf" < "$TMP/pool.log" 2>&1 & PIDS+=($!) +sleep 0.5 +RH=$(curl -s -m 20 -D- -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$P_POOLJ/v1/chat/completions") +contains "$RH" "X-Stub-Auth: Bearer $P_KEY_SECOND" "a 429 on the first key rotates to the second" +SP=$(curl -s -m 10 "http://127.0.0.1:$P_POOLJ/status") +contains "$SP" '"keys":2' "/status shows the pool size" + +echo "== 27. /metrics ==" +# Prometheus-Textformat: der Scraper soll nicht JSON nach Prometheus übersetzen müssen. +MH=$(curl -s -m 10 -D- -o /dev/null "http://127.0.0.1:$P_RETRYJ/metrics") +contains "$MH" "text/plain; version=0.0.4" "/metrics speaks the Prometheus text format" +contains "$M" "junction_endpoint_up{endpoint=\"box\"} 1" "an endpoint that serves is up 1" +contains "$M" "junction_inflight " "the queue is exported" +contains "$M" "junction_cache_hits_total" "cache counters are exported" +if printf '%s' "$M" | grep -qE '^junction_requests_total\{outcome="ok"\} [0-9]+$'; then + ok "every sample line is name{labels} value" +else + bad "every sample line is name{labels} value" +fi + +# Eigener Listener für die Überwachung: dort gibt es nur /metrics. Ein Scraper soll +# die Zahlen sehen, aber nicht über /admin Endpunkte pausieren können. +MM=$(curl -s -m 10 "http://127.0.0.1:$P_MET/metrics") +contains "$MM" "junction_endpoint_up{endpoint=\"box\"}" "the metrics listener serves /metrics" +MX=$(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"x"}]}' \ + "http://127.0.0.1:$P_MET/v1/chat/completions") +[ "$MX" = "404" ] && ok "the metrics listener refuses model traffic (404)" \ + || bad "the metrics listener refuses model traffic (got $MX)" +MA=$(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:$P_MET/admin/pause/box") +[ "$MA" = "404" ] && ok "the metrics listener refuses /admin (404)" \ + || bad "the metrics listener refuses /admin (got $MA)" diff --git a/tests/run.sh b/tests/run.sh index 25c5e62..e75fbca 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -34,7 +34,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8175 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8175 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do if ss -tln 2>/dev/null | grep -q ":$port "; then echo "port $port is busy — a leftover junction/stub is still running:" ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' @@ -648,6 +648,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # shellcheck source=tests/pools.sh . "$(dirname "$0")/pools.sh" +# Wiederholung vor dem Failover, Schlüssel-Pool und /metrics. +# shellcheck source=tests/retry-metrics.sh +. "$(dirname "$0")/retry-metrics.sh" + # Kürzen von Werkzeugausgaben. # shellcheck source=tests/compress.sh . "$(dirname "$0")/compress.sh" diff --git a/tests/stub.c b/tests/stub.c index 838f218..06a0305 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -1,9 +1,15 @@ /* tests/stub.c — OpenAI-compatible stub endpoint for the test suite. * * stub [--fail] [--delay SECONDS] [--tls CERT KEY] + * [--fail-n N] [--deny-auth SUBSTR] * * --fail always answers 503 (an endpoint that is up but will not serve) * --delay waits that long before answering (to exercise "still_working") + * --fail-n answers 503 for the first N requests, then serves — the counter lives in + * $STUB_STATE, so it survives the fork per connection and the test can prove + * that a 5xx is retried on the same endpoint instead of failing over + * --deny-auth answers 429 when the Authorization header contains SUBSTR — the way to + * check that junction rotates to the next key of a pool * * The stub echoes what it received in response headers (X-Stub-*) so the tests can * prove header passthrough and body integrity, including after chunked decoding. @@ -19,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -45,20 +53,48 @@ static const char *find_header(const char *head, const char *name, char *out, si return NULL; } +/* Zählt Anfragen über Prozessgrenzen hinweg — der Stub forkt je Verbindung, ein + * Zähler im Speicher des Vaters wäre für das Kind unsichtbar. Die Datei kommt aus + * $STUB_STATE; ohne sie zählt niemand und --fail-n bleibt wirkungslos. */ +static int request_serial(void) +{ + const char *path = getenv("STUB_STATE"); + if (!path || !*path) return 0; + int fd = open(path, O_RDWR | O_CREAT, 0600); + if (fd < 0) return 0; + if (flock(fd, LOCK_EX) != 0) { close(fd); return 0; } + char b[32] = ""; + ssize_t got = read(fd, b, sizeof b - 1); + int seen = (got > 0) ? atoi(b) : 0; + seen++; + snprintf(b, sizeof b, "%d\n", seen); + if (lseek(fd, 0, SEEK_SET) == 0 && ftruncate(fd, 0) == 0) { + ssize_t w = write(fd, b, strlen(b)); + (void)w; + } + flock(fd, LOCK_UN); + close(fd); + return seen; +} + int main(int argc, char **argv) { if (argc < 3) { - fprintf(stderr, "usage: stub [--fail] [--delay SECONDS]\n"); + fprintf(stderr, "usage: stub [--fail] [--delay SECONDS] [--fail-n N] [--deny-auth SUBSTR]\n"); return 2; } int port = atoi(argv[1]); const char *name = argv[2]; int fail = 0; double delay = 0; + int fail_n = 0; + const char *deny_auth = ""; const char *cert = NULL, *key = NULL; for (int i = 3; i < argc; i++) { if (!strcmp(argv[i], "--fail")) fail = 1; else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]); + else if (!strcmp(argv[i], "--fail-n") && i + 1 < argc) fail_n = atoi(argv[++i]); + else if (!strcmp(argv[i], "--deny-auth") && i + 1 < argc) deny_auth = argv[++i]; else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; } } char tlserr[256]; @@ -124,6 +160,18 @@ int main(int argc, char **argv) if (used == 0) { j_conn_close(&client); _exit(0); } req[used] = '\0'; + /* Zwei künstliche Fehler, ohne die sich Retry und Schlüsselrotation nicht + * nachweisen lassen: ein 503 für die ersten N Anfragen und ein 429 für einen + * bestimmten Schlüssel. */ + char authhdr[256] = ""; + find_header(req, "Authorization", authhdr, sizeof authhdr); + int forced = 0; + /* Nur Chat-Anfragen zählen: junction holt beim Start GET /v1/models, und diese + * eine Anfrage darf das Fehlerkontingent des Tests nicht verbrauchen. */ + int counts = !strncmp(req, "POST", 4) && strstr(req, "/chat/completions"); + if (fail_n > 0 && counts && request_serial() <= fail_n) forced = 503; + else if (deny_auth[0] && strstr(authhdr, deny_auth)) forced = 429; + char *head_end = strstr(req, "\r\n\r\n"); size_t head_len = head_end ? (size_t)(head_end + 4 - req) : used; char cl[32]; @@ -170,7 +218,17 @@ int main(int argc, char **argv) find_header(req, "X-Forwarded-For", fwd, sizeof fwd); char body[1024]; - if (fail) { + if (forced) { + /* Retry-After: 0 — der Stub weiß nicht, wie lange ein echtes Kontingent + * braucht; die 0 macht klar, dass sofort weiterversucht werden darf. */ + const char *b = (forced == 429) ? "{\"error\":\"rate limited\"}" + : "{\"error\":\"not serving yet\"}"; + snprintf(body, sizeof body, + "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nRetry-After: 0\r\n" + "Content-Length: %zu\r\nConnection: close\r\n\r\n%s", + forced, (forced == 429) ? "Too Many Requests" : "Service Unavailable", + strlen(b), b); + } else if (fail) { const char *b = "{\"error\":\"not serving\"}"; snprintf(body, sizeof body, "HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n" @@ -214,9 +272,9 @@ int main(int argc, char **argv) "Content-Length: %zu\r\n" "X-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n" "X-Stub-Custom: %s\r\nX-Stub-Static: %s\r\nX-Stub-Xff: %s\r\n" - "X-Stub-Model: %s\r\n" + "X-Stub-Model: %s\r\nX-Stub-Auth: %s\r\n" "Connection: close\r\n\r\n%s", - strlen(b), name, body_len, custom, static_hdr, fwd, model, b); + strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr, b); } if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0) fprintf(stderr, "stub write failed: %s\n", ioerr);