Eine Regel kann `judge every N <endpoint> as "model" [cache 5m|1h]` tragen. Jede N-te Anfrage einer Unterhaltung geht dann an den Judge, mit demselben Rumpf (also dem vollen Verlauf). Fällt der Judge aus (429, offline, Budget), bleiben die normalen Ziele als Fallback; sie bekommen den Rumpf ohne Cache-Marker. Die Zählung ist pro Unterhaltung und Regel: x-junction-session, x-session-id, x-conversation-id oder x-opencode-session, sonst die erste System- und User-Nachricht. Ein Judge-Turn umgeht den Antwort-Cache. `cache 1h` setzt einen Anthropic-cache_control-Marker auf die letzte Nachricht, damit Tools + System + Prefix wiederverwendet werden; 5m ist die kürzere TTL, off sendet keinen Marker. Das virtuelle Modell erscheint in /v1/models mit der engeren Grenze von Worker und Judge. Der OpenAI-kompatible Anthropic-Endpoint (kind remote) macht Claude als Judge von einem OpenAI-Client aus erreichbar. Tests: 334 OK, 0 FAIL.
4379 lines
185 KiB
C
4379 lines
185 KiB
C
/* junction/junction.c — HTTP surface, rule routing, hooks, forwarding, caching.
|
|
*
|
|
* C99 + POSIX (+ OpenSSL when built with TLS). One request at a time on purpose.
|
|
*
|
|
* All socket I/O goes through j_conn, so TLS is a property of the connection, not a
|
|
* branch in the request path. Bodies are parsed out of a j_buf so bytes that arrive
|
|
* together with the headers are never lost again.
|
|
*/
|
|
#define _POSIX_C_SOURCE 200809L
|
|
|
|
#include "cache.h"
|
|
#include "mesh.h"
|
|
#include "opencode.h"
|
|
#include "price.h"
|
|
#include "compress.h"
|
|
#include "config.h"
|
|
#include "models.h"
|
|
#include "judge.h"
|
|
#include "mcp.h"
|
|
#include "control.h"
|
|
|
|
void j_control_ops_install(void);
|
|
#include "conn.h"
|
|
#include "http.h"
|
|
#include "effort.h"
|
|
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <fnmatch.h>
|
|
#include <netdb.h>
|
|
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <poll.h>
|
|
#include <pthread.h>
|
|
#include <signal.h>
|
|
#include <stdarg.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/types.h>
|
|
#include <sys/wait.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#define HDR_BLOCK_MAX 32768
|
|
#define RELAY_CHUNK 8192
|
|
|
|
j_config CFG; /* nicht static: der Steuerkanal liest dieselbe Konfiguration */
|
|
|
|
/* One lock for stderr (so log lines never interleave) and one for the runtime state
|
|
* of the endpoints. The config itself is read-only after startup. */
|
|
static pthread_mutex_t g_log_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
static pthread_mutex_t g_state_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
/* Regeln werden im Betrieb geändert, während Anfragen sie lesen. Ein Zeiger in
|
|
* das Array wäre dann irgendwann ins Leere gerichtet — deshalb wird die passende
|
|
* Regel unter Lesesperre kopiert und danach ohne Sperre benutzt. */
|
|
static pthread_rwlock_t g_rules_rw = PTHREAD_RWLOCK_INITIALIZER;
|
|
|
|
/* Which connection, if any, wants a heartbeat from THIS thread right now. A thread
|
|
* handles one request, so this is per-request state, not global. */
|
|
/* Angaben, die den Anfragepfad nie verlassen, aber in die Logzeile gehören:
|
|
* Wartezeit in der Schlange, Zahl der Wiederholungen, Trefferregel. Thread-lokal, weil
|
|
* jeder Request in einem eigenen Faden läuft — kein Sperren, keine Reihenfolge. */
|
|
static __thread long t_queue_ms;
|
|
static __thread int t_req_retries;
|
|
static __thread int t_rule_line;
|
|
/* Was der Anbieter als Retry-After geschickt hat (Sekunden, 0 = nichts gesagt).
|
|
* Thread-lokal wie der Rest: es gehört zu genau dieser Anfrage. */
|
|
static __thread int t_retry_after_s;
|
|
|
|
static __thread j_conn *t_heartbeat;
|
|
static __thread double t_heartbeat_started;
|
|
|
|
#define STATE_LOCK() pthread_mutex_lock(&g_state_mu)
|
|
#define STATE_UNLOCK() pthread_mutex_unlock(&g_state_mu)
|
|
|
|
/* Free upstream slots. A request waits here instead of being refused, and a streaming
|
|
* caller is told why it is waiting — as an SSE comment, which every conformant parser
|
|
* drops on the floor. */
|
|
static struct {
|
|
pthread_mutex_t mu;
|
|
pthread_cond_t cv;
|
|
int inflight;
|
|
int waiting;
|
|
} SLOTS = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0 };
|
|
|
|
/* Drain: bei SIGTERM gibt junction den Port auf und beendet nur noch, was schon
|
|
* läuft. g_stop wird vom Signalhandler gesetzt, g_draining von der Hauptschleife —
|
|
* /status und /metrics lesen es, ohne den Handler zu kennen. */
|
|
static volatile sig_atomic_t g_stop;
|
|
static volatile sig_atomic_t g_draining;
|
|
|
|
static void on_term(int sig)
|
|
{
|
|
(void)sig;
|
|
if (g_draining) {
|
|
/* Zweites Signal: nicht mehr auf laufende Requests warten. */
|
|
g_stop = 1;
|
|
} else {
|
|
/* Erstes Signal: Listener bleibt offen, neue Requests bekommen
|
|
* "restarting" mit Retry-After; laufende duerfen fertig werden. */
|
|
g_draining = 1;
|
|
}
|
|
}
|
|
|
|
/* Waehrend des Neustarts bekommt jeder neue Request eine klare Antwort statt
|
|
* eines abgebrochenen Sockets: 503 + Retry-After + X-Junction-Restarting.
|
|
* So kann ein Client "junction restarting, retry in N s" anzeigen. */
|
|
static void send_restarting(j_conn *c)
|
|
{
|
|
const char *body = "{\"error\":\"restarting\",\"retry_after_s\":5,"
|
|
"\"hint\":\"junction is restarting; retry after Retry-After\"}";
|
|
char hdr[512];
|
|
int n = snprintf(hdr, sizeof hdr,
|
|
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n"
|
|
"Retry-After: 5\r\nX-Junction-Restarting: true\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n",
|
|
strlen(body));
|
|
char err[128];
|
|
if (j_conn_write(c, hdr, (size_t)n, err, sizeof err) >= 0)
|
|
(void)j_conn_write(c, body, strlen(body), err, sizeof err);
|
|
}
|
|
|
|
static int drain_inflight(void)
|
|
{
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
int n = SLOTS.inflight;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
return n;
|
|
}
|
|
|
|
static const double g_lat_bounds[J_LAT_BUCKETS] = J_LAT_BOUNDS;
|
|
|
|
/* In welchen Eimer fällt diese Dauer? J_LAT_BUCKETS selbst heißt +Inf. */
|
|
static int lat_bucket_index(double sec)
|
|
{
|
|
for (int i = 0; i < J_LAT_BUCKETS; i++)
|
|
if (sec <= g_lat_bounds[i]) return i;
|
|
return J_LAT_BUCKETS;
|
|
}
|
|
|
|
/* p95 aus dem Histogramm: die obere Grenze des Eimers, in dem die 95-Prozent-Marke
|
|
* liegt. Das ist eine Obergrenze, keine Messung — und steht deshalb im Namen. */
|
|
static double lat_p95_ms(const j_endpoint *ep)
|
|
{
|
|
if (ep->lat_n == 0) return -1.0;
|
|
unsigned long want = (unsigned long)((double)ep->lat_n * 0.95);
|
|
if (want == 0) want = 1;
|
|
unsigned long cum = 0;
|
|
for (int i = 0; i < J_LAT_BUCKETS; i++) {
|
|
cum += ep->lat_bucket[i];
|
|
if (cum >= want) return g_lat_bounds[i] * 1000.0;
|
|
}
|
|
return -1.0; /* nur im +Inf-Eimer: keine Aussage außer "über 60 s" */
|
|
}
|
|
|
|
/* Ein Platz je (Endpunkt, Modell). Eine Box, die ein Modell geladen hält, bedient es
|
|
* einmal gleichzeitig; die zweite Anfrage wartet, statt die Maschine in den Swap zu
|
|
* treiben. Vier Modelle sind damit vier parallele Anfragen — ohne dass jemand
|
|
* Konfiguration nachzählt: max_model_inflight steht am Endpunkt. */
|
|
#define MODEL_SLOTS 64
|
|
|
|
static double now_s(void);
|
|
|
|
static struct {
|
|
pthread_mutex_t mu;
|
|
pthread_cond_t cv;
|
|
struct { char ep[J_NAME_MAX]; char model[J_GLOB_MAX]; int n; } slot[MODEL_SLOTS];
|
|
} MODEL_GATE = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
|
|
|
|
static int model_gate_acquire(const char *ep, const char *model, int limit, double timeout_s)
|
|
{
|
|
if (limit <= 0) return 0;
|
|
double deadline = now_s() + timeout_s;
|
|
int idx = -1;
|
|
pthread_mutex_lock(&MODEL_GATE.mu);
|
|
for (;;) {
|
|
int free_slot = -1, current = 0;
|
|
for (int i = 0; i < MODEL_SLOTS; i++) {
|
|
if (MODEL_GATE.slot[i].ep[0] &&
|
|
!strcmp(MODEL_GATE.slot[i].ep, ep) &&
|
|
!strcmp(MODEL_GATE.slot[i].model, model)) {
|
|
idx = i;
|
|
current = MODEL_GATE.slot[i].n;
|
|
break;
|
|
}
|
|
if (!MODEL_GATE.slot[i].ep[0] && free_slot < 0) free_slot = i;
|
|
}
|
|
if (current < limit) {
|
|
if (idx < 0) {
|
|
if (free_slot < 0) { /* Tabelle voll: nicht blockieren */
|
|
pthread_mutex_unlock(&MODEL_GATE.mu);
|
|
return 0;
|
|
}
|
|
idx = free_slot;
|
|
snprintf(MODEL_GATE.slot[idx].ep, sizeof MODEL_GATE.slot[idx].ep, "%s", ep);
|
|
snprintf(MODEL_GATE.slot[idx].model, sizeof MODEL_GATE.slot[idx].model,
|
|
"%s", model);
|
|
MODEL_GATE.slot[idx].n = 0;
|
|
}
|
|
MODEL_GATE.slot[idx].n++;
|
|
pthread_mutex_unlock(&MODEL_GATE.mu);
|
|
return 0;
|
|
}
|
|
double left = deadline - now_s();
|
|
if (left <= 0) {
|
|
pthread_mutex_unlock(&MODEL_GATE.mu);
|
|
return -1;
|
|
}
|
|
struct timespec ts;
|
|
clock_gettime(CLOCK_REALTIME, &ts);
|
|
double step = left < 1.0 ? left : 1.0;
|
|
ts.tv_sec += (time_t)step;
|
|
ts.tv_nsec += (long)((step - (time_t)step) * 1e9);
|
|
if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
|
|
pthread_cond_timedwait(&MODEL_GATE.cv, &MODEL_GATE.mu, &ts);
|
|
idx = -1;
|
|
}
|
|
}
|
|
|
|
static void model_gate_release(const char *ep, const char *model, int limit)
|
|
{
|
|
if (limit <= 0) return;
|
|
pthread_mutex_lock(&MODEL_GATE.mu);
|
|
for (int i = 0; i < MODEL_SLOTS; i++) {
|
|
if (MODEL_GATE.slot[i].ep[0] && !strcmp(MODEL_GATE.slot[i].ep, ep) &&
|
|
!strcmp(MODEL_GATE.slot[i].model, model)) {
|
|
if (--MODEL_GATE.slot[i].n <= 0) {
|
|
MODEL_GATE.slot[i].ep[0] = '\0';
|
|
MODEL_GATE.slot[i].model[0] = '\0';
|
|
MODEL_GATE.slot[i].n = 0;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
pthread_cond_broadcast(&MODEL_GATE.cv);
|
|
pthread_mutex_unlock(&MODEL_GATE.mu);
|
|
}
|
|
|
|
static double now_s(void)
|
|
{
|
|
struct timespec ts;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
|
}
|
|
|
|
/* MCP-Modul schreibt über dieselbe Senke wie alles andere. */
|
|
static void mcp_log_bridge(const char *event, const char *msg);
|
|
|
|
static void jlog(const char *event, const char *fmt, ...)
|
|
{
|
|
char line[1024];
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
int n = vsnprintf(line, sizeof line, fmt, ap);
|
|
va_end(ap);
|
|
pthread_mutex_lock(&g_log_mu);
|
|
fprintf(stderr, "[%s] %s%s%s\n", CFG.log_prefix, event, n > 0 ? " " : "",
|
|
n > 0 ? line : "");
|
|
fflush(stderr);
|
|
pthread_mutex_unlock(&g_log_mu);
|
|
}
|
|
|
|
static void mcp_log_bridge(const char *event, const char *msg)
|
|
{
|
|
jlog(event, "%s", msg);
|
|
}
|
|
|
|
static void json_escape(const char *in, char *out, size_t outlen)
|
|
{
|
|
size_t o = 0;
|
|
for (const char *p = in; *p && o + 2 < outlen; p++) {
|
|
unsigned char c = (unsigned char)*p;
|
|
if (c == '"' || c == '\\') { out[o++] = '\\'; out[o++] = (char)c; }
|
|
else if (c < 0x20) { out[o++] = ' '; }
|
|
else out[o++] = (char)c;
|
|
}
|
|
out[o] = '\0';
|
|
}
|
|
|
|
/* -------------------------------------------------------------- token sizing */
|
|
static long json_int_value(const char *body, const char *key)
|
|
{
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(body, pat);
|
|
if (!p) return -1;
|
|
p += strlen(pat);
|
|
while (*p && (*p == ':' || isspace((unsigned char)*p))) p++;
|
|
if (!isdigit((unsigned char)*p)) return -1;
|
|
return strtol(p, NULL, 10);
|
|
}
|
|
|
|
static int json_bool_value(const char *body, const char *key)
|
|
{
|
|
if (!body) return 0;
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(body, pat);
|
|
if (!p) return 0;
|
|
p += strlen(pat);
|
|
while (*p && (*p == ':' || isspace((unsigned char)*p))) p++;
|
|
return !strncmp(p, "true", 4);
|
|
}
|
|
|
|
/* Liest eine Zahl. Rückgabe: 1 = gefunden, 0 = nicht vorhanden, -1 = kein Wert. */
|
|
static int json_num_value(const char *body, const char *key, double *out)
|
|
{
|
|
if (!body) return 0;
|
|
char pat[64];
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = strstr(body, pat);
|
|
if (!p) return 0;
|
|
p += strlen(pat);
|
|
while (*p && (*p == ':' || isspace((unsigned char)*p) || *p == '"')) p++;
|
|
if (!*p) return -1;
|
|
char *end = NULL;
|
|
double v = strtod(p, &end);
|
|
if (end == p) return -1;
|
|
*out = v;
|
|
return 1;
|
|
}
|
|
|
|
static void json_str_value(const char *body, const char *key, char *out, size_t outlen)
|
|
{
|
|
char pat[64];
|
|
out[0] = '\0';
|
|
snprintf(pat, sizeof pat, "\"%s\"", key);
|
|
const char *p = body ? strstr(body, pat) : NULL;
|
|
if (!p) return;
|
|
p += strlen(pat);
|
|
while (*p && (*p == ':' || isspace((unsigned char)*p))) p++;
|
|
if (*p != '"') return;
|
|
p++;
|
|
size_t i = 0;
|
|
while (*p && *p != '"' && i < outlen - 1) {
|
|
if (*p == '\\' && p[1]) p++;
|
|
out[i++] = *p++;
|
|
}
|
|
out[i] = '\0';
|
|
}
|
|
|
|
/* How much output did the CLIENT ask for? Nothing else.
|
|
*
|
|
* junction is a pass-through: it does not tokenise, does not estimate from character
|
|
* counts, and never invents a size for a request that did not state one. So `need` is
|
|
* either the max_tokens/max_completion_tokens the client wrote, or unknown (-1) — and
|
|
* an endpoint's `context` is only compared against a number the client actually sent.
|
|
* Guessing here is how a 2048-context embedding endpoint ends up refusing requests
|
|
* that carry no token budget at all.
|
|
*/
|
|
static long declared_max_tokens(const char *body)
|
|
{
|
|
if (!body) return -1;
|
|
long mt = json_int_value(body, "max_tokens");
|
|
if (mt < 0) mt = json_int_value(body, "max_completion_tokens");
|
|
return mt;
|
|
}
|
|
|
|
/* Sucht im Bereich [b, e) nach einem Bild-Inhalt. Erkannt wird ein "type"-Feld mit
|
|
* dem Wert image_url, input_image oder image. Clients, die den Typ weglassen, schicken
|
|
* "image_url" direkt gefolgt von einem Objekt oder einer Zeichenkette — auch das zählt.
|
|
* Escapte Erwähnungen in Werkzeugausgaben ("\"type\":\"image_url\"") treffen bewusst
|
|
* nicht: zwischen `type` und dem Doppelpunkt steht dort ein Backslash. */
|
|
static int region_has_image(const char *b, const char *e)
|
|
{
|
|
for (const char *p = strstr(b, "\"type\""); p && p < e; p = strstr(p + 6, "\"type\"")) {
|
|
const char *v = p + 6;
|
|
while (v < e && (*v == ':' || isspace((unsigned char)*v))) v++;
|
|
if (v >= e || *v != '"') continue;
|
|
v++;
|
|
if (!strncmp(v, "image_url\"", 10)) return 1;
|
|
if (!strncmp(v, "input_image\"", 12)) return 1;
|
|
if (!strncmp(v, "image\"", 6)) return 1;
|
|
}
|
|
for (const char *p = strstr(b, "\"image_url\""); p && p < e;
|
|
p = strstr(p + 11, "\"image_url\"")) {
|
|
const char *v = p + 11;
|
|
while (v < e && (*v == ':' || isspace((unsigned char)*v))) v++;
|
|
if (v < e && (*v == '{' || *v == '"')) return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* Trägt die Anfrage ein Bild? Ein Textmodell, das so einen Rumpf bekommt, antwortet oft
|
|
* mit leerem Inhalt statt mit einem Fehler — deshalb muss die Zustellung vorher
|
|
* entschieden werden, nicht hinterher bemerkt.
|
|
*
|
|
* Gesucht wird nur in den Nachrichten, nicht im ganzen Rumpf. Ein Rumpf-Scan machte jede
|
|
* Anfrage mit Werkzeugen zu einer Bildanfrage, weil Werkzeug-Schemata Parameter namens
|
|
* `image_url` beschreiben (Hermes' vision_analyze tut das): die Anfrage landete damit in
|
|
* der Bildkette, wo ein kleiner lokaler Knoten am Kontext scheitert und der einzige
|
|
* Cloud-Knoten bei Ueberlast 429 liefert — der Client sah "provider unavailable", obwohl
|
|
* die Textkette daneben gesund war. Fehlt ein messages-Array (andere Rumpfform), wird
|
|
* weiter der ganze Rumpf geprüft: lieber ein Bild zu viel als eines, das beim
|
|
* Textmodell landet. */
|
|
static int body_has_image(const char *body)
|
|
{
|
|
if (!body) return 0;
|
|
size_t len = strlen(body);
|
|
size_t as = 0, ae = 0;
|
|
if (jcomp_find_messages(body, len, &as, &ae) == 0)
|
|
return region_has_image(body + as, body + ae);
|
|
return region_has_image(body, body + len);
|
|
}
|
|
|
|
/* Geschätzte Prompt-Größe in Token.
|
|
*
|
|
* Das ist eine Schätzung und heißt auch so: Zeichen geteilt durch
|
|
* ctx_chars_per_token. Zwei Dinge macht sie brauchbar, ohne sie zu einer Messung zu
|
|
* erklären:
|
|
* 1. Base64-Bilddaten werden übersprungen. Sonst zählt ein 4-MB-Foto als eine
|
|
* Million Token und jede Regel greift daneben.
|
|
* 2. Ohne ctx_chars_per_token gibt es keine Schätzung, sondern -1. Der Parser
|
|
* lehnt dann Regeln mit ctx-Bedingung ab, statt sie still nie greifen zu lassen.
|
|
*/
|
|
static long estimate_ctx_tokens(const char *body, size_t len, double chars_per_token)
|
|
{
|
|
if (!body || chars_per_token <= 0) return -1;
|
|
size_t counted = len;
|
|
const char *p = body;
|
|
while ((p = strstr(p, ";base64,")) != NULL) {
|
|
const char *q = p + 8;
|
|
while (*q && *q != '"') q++;
|
|
counted -= (size_t)(q - p);
|
|
p = q;
|
|
}
|
|
return (long)((double)counted / chars_per_token + 0.5);
|
|
}
|
|
|
|
|
|
/* ------------------------------------------------------------------- request */
|
|
typedef struct {
|
|
char method[16];
|
|
char path[2048];
|
|
j_hdrs hdrs;
|
|
char *body;
|
|
size_t body_len;
|
|
} j_req;
|
|
|
|
static int wait_readable(j_conn *c, double idle_s, double deadline)
|
|
{
|
|
for (;;) {
|
|
if (j_conn_pending(c) > 0) return 1;
|
|
if (now_s() >= deadline) return 0;
|
|
double left = deadline - now_s();
|
|
double t = left < idle_s ? left : idle_s;
|
|
struct pollfd p = { .fd = c->fd, .events = POLLIN, .revents = 0 };
|
|
int rc = poll(&p, 1, (int)(t * 1000.0) + 1);
|
|
if (rc < 0) { if (errno == EINTR) continue; return -1; }
|
|
if (rc == 0) { jlog("still_working", "side=wait silent_s=%.1f", idle_s); continue; }
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
/* Read a request head + body. Returns 0, or -1 with `err` filled. */
|
|
static int read_request(j_conn *c, j_buf *buf, j_req *rq, char *err, size_t errlen)
|
|
{
|
|
memset(rq, 0, sizeof *rq);
|
|
j_hdrs_init(&rq->hdrs);
|
|
j_buf_reset(buf);
|
|
|
|
double deadline = now_s() + 120.0;
|
|
ssize_t head_len = j_buf_read_until(c, buf, "\r\n\r\n", HDR_BLOCK_MAX, 60.0, deadline,
|
|
err, errlen);
|
|
if (head_len <= 0) return -1;
|
|
size_t body_off = (size_t)head_len;
|
|
|
|
char *line_end = strstr(buf->data, "\r\n");
|
|
if (!line_end) { snprintf(err, errlen, "bad_request_line"); return -1; }
|
|
size_t line_len = (size_t)(line_end - buf->data);
|
|
char line[2200];
|
|
if (line_len >= sizeof line) { snprintf(err, errlen, "request_line_too_long"); return -1; }
|
|
memcpy(line, buf->data, line_len);
|
|
line[line_len] = '\0';
|
|
if (sscanf(line, "%15s %2047s", rq->method, rq->path) != 2) {
|
|
snprintf(err, errlen, "bad_request_line");
|
|
return -1;
|
|
}
|
|
|
|
const char *hdr_start = line_end + 2;
|
|
size_t hdr_len = (size_t)((buf->data + head_len - 4) - hdr_start);
|
|
j_hdrs_parse(&rq->hdrs, hdr_start, hdr_len);
|
|
|
|
char te[J_HDR_VALUE], cl[J_HDR_VALUE];
|
|
int chunked = !j_hdrs_find(&rq->hdrs, "Transfer-Encoding", te, sizeof te) &&
|
|
strstr(te, "chunked") != NULL;
|
|
long content_length = -1;
|
|
if (!j_hdrs_find(&rq->hdrs, "Content-Length", cl, sizeof cl))
|
|
content_length = strtol(cl, NULL, 10);
|
|
|
|
if (chunked) {
|
|
if (j_chunked_read(c, buf, body_off, (size_t)CFG.max_body_bytes, 30.0,
|
|
now_s() + 120.0, &rq->body, &rq->body_len, err, errlen))
|
|
return -1;
|
|
return 0;
|
|
}
|
|
if (content_length <= 0) { rq->body = NULL; rq->body_len = 0; return 0; }
|
|
if (content_length > CFG.max_body_bytes) { snprintf(err, errlen, "body_too_large"); return -1; }
|
|
if (j_buf_ensure(c, buf, body_off, (size_t)content_length, 30.0, now_s() + 120.0,
|
|
err, errlen))
|
|
return -1;
|
|
rq->body = malloc((size_t)content_length + 1);
|
|
if (!rq->body) { snprintf(err, errlen, "oom"); return -1; }
|
|
memcpy(rq->body, buf->data + body_off, (size_t)content_length);
|
|
rq->body[(size_t)content_length] = '\0';
|
|
rq->body_len = (size_t)content_length;
|
|
return 0;
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- SSE */
|
|
/* A streaming caller gets its response head immediately, then nothing but comments
|
|
* until there is something real to say. Comments are part of the SSE spec and MUST be
|
|
* ignored by a parser, so a client that only understands events never sees them; a
|
|
* human with curl sees exactly what the router is doing. */
|
|
static int sse_open(j_conn *client)
|
|
{
|
|
char err[128];
|
|
const char *head = "HTTP/1.1 200 OK\r\n"
|
|
"Content-Type: text/event-stream\r\n"
|
|
"Cache-Control: no-cache\r\n"
|
|
"X-Accel-Buffering: no\r\n"
|
|
"Connection: close\r\n\r\n";
|
|
return j_conn_write(client, head, strlen(head), err, sizeof err) < 0 ? -1 : 0;
|
|
}
|
|
|
|
static int sse_comment(j_conn *client, const char *fmt, ...)
|
|
{
|
|
char line[512];
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
int n = vsnprintf(line, sizeof line - 3, fmt, ap);
|
|
va_end(ap);
|
|
if (n < 0) return -1;
|
|
if ((size_t)n > sizeof line - 4) n = (int)sizeof line - 4;
|
|
/* ": ...\n\n" — one comment line, terminated like an event */
|
|
memmove(line + 2, line, (size_t)n);
|
|
line[0] = ':';
|
|
line[1] = ' ';
|
|
line[(size_t)n + 2] = '\n';
|
|
line[(size_t)n + 3] = '\n';
|
|
char err[128];
|
|
return j_conn_write(client, line, (size_t)n + 4, err, sizeof err) < 0 ? -1 : 0;
|
|
}
|
|
|
|
/* When the head is already out, failures have to travel as events. */
|
|
static void sse_error(j_conn *client, int status, const char *message)
|
|
{
|
|
char body[1024], esc[768];
|
|
size_t o = 0;
|
|
for (const char *q = message; *q && o + 2 < sizeof esc; q++) {
|
|
if (*q == '"' || *q == '\\') { esc[o++] = '\\'; esc[o++] = *q; }
|
|
else if ((unsigned char)*q < 0x20) esc[o++] = ' ';
|
|
else esc[o++] = *q;
|
|
}
|
|
esc[o] = '\0';
|
|
snprintf(body, sizeof body,
|
|
"data: {\"error\":{\"message\":\"%s\",\"type\":\"junction_error\",\"code\":%d}}\n\n"
|
|
"data: [DONE]\n\n", esc, status);
|
|
char err[128];
|
|
(void)j_conn_write(client, body, strlen(body), err, sizeof err);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------- slots */
|
|
/* Returns 0 on a free slot, -1 on timeout or when the client went away. */
|
|
static int slot_acquire(j_conn *client, int streaming, double timeout_s,
|
|
const char *why)
|
|
{
|
|
double deadline = now_s() + timeout_s;
|
|
int announced = 0, ahead = -1;
|
|
struct timespec ts;
|
|
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
while (SLOTS.inflight >= CFG.max_inflight) {
|
|
if (!announced) {
|
|
ahead = SLOTS.waiting + 1;
|
|
SLOTS.waiting++;
|
|
announced = 1;
|
|
if (streaming && sse_comment(client, "junction: waiting for a free slot (%d ahead of you)",
|
|
ahead - 1) < 0) {
|
|
SLOTS.waiting--;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
return -1;
|
|
}
|
|
jlog("queued", "reason=%s ahead=%d max_inflight=%d", why, ahead - 1,
|
|
CFG.max_inflight);
|
|
}
|
|
clock_gettime(CLOCK_REALTIME, &ts);
|
|
double left = deadline - now_s();
|
|
if (left <= 0) break;
|
|
double step = left < 2.0 ? left : 2.0;
|
|
ts.tv_sec += (time_t)step;
|
|
ts.tv_nsec += (long)((step - (time_t)step) * 1e9);
|
|
if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
|
|
int rc = pthread_cond_timedwait(&SLOTS.cv, &SLOTS.mu, &ts);
|
|
if (rc != 0 && now_s() >= deadline) break;
|
|
if (streaming && announced) {
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
/* the write must not happen under the slot lock */
|
|
if (sse_comment(client, "junction: still waiting (%.0fs, %d ahead)",
|
|
now_s() - (deadline - timeout_s), ahead - 1) < 0) {
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
SLOTS.waiting--;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
return -1;
|
|
}
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
}
|
|
}
|
|
if (SLOTS.inflight >= CFG.max_inflight) {
|
|
if (announced) SLOTS.waiting--;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
if (streaming)
|
|
sse_error(client, 429, "junction: no free slot within the queue timeout");
|
|
return -1;
|
|
}
|
|
if (announced) SLOTS.waiting--;
|
|
SLOTS.inflight++;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
return 0;
|
|
}
|
|
|
|
static void slot_release(void)
|
|
{
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
if (SLOTS.inflight > 0) SLOTS.inflight--;
|
|
pthread_cond_broadcast(&SLOTS.cv);
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ respond */
|
|
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: %s\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n",
|
|
code, reason, ctype, len);
|
|
char err[128];
|
|
if (j_conn_write(c, hdr, (size_t)n, err, sizeof err) < 0) return;
|
|
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
|
|
* Anbieter ihn ausweist, die zwischengespeicherte Eingabe. Fehlt der Block, gibt es
|
|
* nichts zu zählen — dann wird auch nichts erfunden. */
|
|
static int usage_from_body(const char *body, size_t len, long *in, long *out, long *cached)
|
|
{
|
|
if (!body || !len) return 0;
|
|
const char *u = strstr(body, "\"usage\"");
|
|
if (!u) return 0;
|
|
const char *end = body + len;
|
|
|
|
const char *p = strstr(u, "\"prompt_tokens\"");
|
|
if (!p || p > end) return 0;
|
|
p = strchr(p, ':');
|
|
if (!p) return 0;
|
|
*in = strtol(p + 1, NULL, 10);
|
|
|
|
p = strstr(u, "\"completion_tokens\"");
|
|
if (!p || p > end) return 0;
|
|
p = strchr(p, ':');
|
|
if (!p) return 0;
|
|
*out = strtol(p + 1, NULL, 10);
|
|
|
|
*cached = 0;
|
|
p = strstr(u, "\"cached_tokens\"");
|
|
if (p && p < end) {
|
|
p = strchr(p, ':');
|
|
if (p) *cached = strtol(p + 1, NULL, 10);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
/* Wie viel das Kürzen insgesamt gespart hat. Ohne diese Zahl wäre die Funktion eine
|
|
* Behauptung: man sieht nur, dass es passiert, nicht ob es hilft. */
|
|
static unsigned long g_tokens_in, g_tokens_out, g_tokens_cached;
|
|
static double g_cost_usd;
|
|
static unsigned long g_cost_unknown;
|
|
|
|
/* Zähler für den Steuerkanal und das Dashboard. Sie zählen, was junction selbst
|
|
* gesehen hat — keine Schätzung, keine Hochrechnung. */
|
|
static unsigned long g_req_ok, g_req_fail;
|
|
static unsigned long g_req_bytes, g_resp_bytes;
|
|
static double g_latency_ms_sum;
|
|
static unsigned long g_latency_n;
|
|
|
|
/* Schaetzung, wie lange ein neu ankommender Request auf einen Slot warten
|
|
* muss: Position in der Queue mal durchschnittliche Dauer geteilt durch die
|
|
* Anzahl paralleler Slots. Wird fuer /status (eta_s) und fuer den
|
|
* Retry-After-Header bei queue_timeout verwendet. */
|
|
static double estimated_wait_s(void)
|
|
{
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
int waiting = SLOTS.waiting;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
double avg_ms = (g_latency_n > 0) ? (g_latency_ms_sum / (double)g_latency_n) : 1000.0;
|
|
if (avg_ms < 100.0) avg_ms = 100.0;
|
|
int maxinf = CFG.max_inflight > 0 ? CFG.max_inflight : 1;
|
|
double eta = (double)(waiting + 1) * avg_ms / 1000.0 / (double)maxinf;
|
|
if (eta < 1.0) eta = 1.0;
|
|
if (eta > CFG.queue_timeout_s) eta = CFG.queue_timeout_s;
|
|
return eta;
|
|
}
|
|
static double g_started_at;
|
|
|
|
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;
|
|
/* Wie oft ein Request auf die Rückkehr der Kette gewartet hat, statt sofort zu scheitern. */
|
|
static unsigned long g_offline_waits;
|
|
/* Wie oft der Wächter eine Anfrage abgelehnt hat. */
|
|
static unsigned long g_guard_refused;
|
|
|
|
/* ---------------------------------------------------------------- Spend-Log */
|
|
/* Eine Zeile je bedienter Anfrage. Das ist die einzige Stelle, an der steht, wer
|
|
* wann was verbraucht hat — /status zählt nur im Speicher, und ein Budget, das beim
|
|
* Neustart wieder voll ist, ist keins. */
|
|
static pthread_mutex_t g_spend_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
static double month_start_ts(void)
|
|
{
|
|
time_t now = time(NULL);
|
|
struct tm tmv;
|
|
gmtime_r(&now, &tmv);
|
|
/* In UTC gerechnet: kein Sommerzeit-Sprung, kein timegm() nötig. */
|
|
return (double)(now - (time_t)((tmv.tm_mday - 1) * 86400 + tmv.tm_hour * 3600 +
|
|
tmv.tm_min * 60 + tmv.tm_sec));
|
|
}
|
|
|
|
/* Der Anteil, der beim Anbieter lag: die ganze Anfrage abzüglich der Wartezeit in der
|
|
* Schlange. Nicht gemessen, sondern hergeleitet — deshalb steht das im Kommentar und
|
|
* nicht nur im Log. */
|
|
static double upstream_part(double latency_ms)
|
|
{
|
|
return latency_ms > (double)t_queue_ms ? latency_ms - (double)t_queue_ms : 0.0;
|
|
}
|
|
|
|
/* Eine Zeile je bedienter Anfrage: Verbrauch für die Budgets, alles andere für die
|
|
* Fehlersuche. Dieselbe Datei für beides — zwei Protokolle über denselben Vorgang wären
|
|
* zwei Wahrheiten, und die eine wäre immer die ältere.
|
|
*
|
|
* `cache` sagt, woher die Antwort kam (off/miss/hit/joined/peer), `latency_ms` ist die
|
|
* ganze Anfrage aus Sicht des Clients, `upstream_ms` der Anteil beim Anbieter,
|
|
* `queue_ms` die Wartezeit auf einen Platz. Eine Zeile pro Anfrage ist dieselbe Menge
|
|
* wie vorher — die Felder sind neu, nicht die Zeilen. */
|
|
static void reqlog_append(const char *vkey, const char *model, const char *ep, int status,
|
|
double latency_ms, double upstream_ms, long queue_ms,
|
|
int rule_line, const char *cache, int retries,
|
|
long in, long out, long cached, double cost)
|
|
{
|
|
if (!CFG.spend_log[0]) return;
|
|
char line[1280], em[J_GLOB_MAX], ev[J_NAME_MAX], ee[J_NAME_MAX];
|
|
json_escape(model ? model : "", em, sizeof em);
|
|
json_escape(vkey ? vkey : "", ev, sizeof ev);
|
|
json_escape(ep ? ep : "", ee, sizeof ee);
|
|
int n = snprintf(line, sizeof line,
|
|
"{\"ts\":%.0f,\"vkey\":\"%s\",\"model\":\"%s\",\"endpoint\":\"%s\","
|
|
"\"status\":%d,\"latency_ms\":%.0f,\"upstream_ms\":%.0f,\"queue_ms\":%ld,"
|
|
"\"rule_line\":%d,\"cache\":\"%s\",\"retries\":%d,"
|
|
"\"tokens_in\":%ld,\"tokens_out\":%ld,\"tokens_cached\":%ld,\"cost_usd\":%.6f}\n",
|
|
/* 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, ee, status, latency_ms, upstream_ms, queue_ms,
|
|
rule_line, cache && cache[0] ? cache : "off", retries, 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);
|
|
if (fd >= 0) {
|
|
ssize_t w = write(fd, line, (size_t)n);
|
|
(void)w;
|
|
close(fd);
|
|
}
|
|
pthread_mutex_unlock(&g_spend_mu);
|
|
}
|
|
|
|
/* Rechnet die Kosten des laufenden Monats auf die vkeys. Fehlt die Datei, ist das
|
|
* kein Fehler: dann hat niemand bisher etwas verbraucht. */
|
|
static void spend_load(void)
|
|
{
|
|
if (!CFG.spend_log[0]) return;
|
|
FILE *f = fopen(CFG.spend_log, "r");
|
|
if (!f) return;
|
|
double month = month_start_ts();
|
|
char line[1024];
|
|
int used = 0;
|
|
double total = 0.0;
|
|
while (fgets(line, sizeof line, f)) {
|
|
const char *ts = strstr(line, "\"ts\":");
|
|
const char *cost = strstr(line, "\"cost_usd\":");
|
|
char who[J_NAME_MAX] = "";
|
|
if (!ts || !cost) continue;
|
|
if (strtod(ts + 5, NULL) < month) continue;
|
|
json_str_value(line, "vkey", who, sizeof who);
|
|
if (!who[0]) continue;
|
|
double c = strtod(cost + 11, NULL);
|
|
for (int i = 0; i < CFG.vkey_count; i++) {
|
|
if (strcmp(CFG.vkeys[i].name, who)) continue;
|
|
CFG.vkeys[i].spent_usd += c;
|
|
used++;
|
|
total += c;
|
|
break;
|
|
}
|
|
}
|
|
fclose(f);
|
|
if (used) jlog("spend", "loaded=%d cost_usd=%.4f month_start=%.0f", used, total, month);
|
|
}
|
|
|
|
/* 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)
|
|
{
|
|
size_t cap = 8192 + (size_t)CFG.endpoint_count * 1400 + (size_t)CFG.rule_count * 220 +
|
|
(size_t)CFG.vkey_count * 420;
|
|
char *out = calloc(1, cap);
|
|
if (!out) { *len_out = 0; return NULL; }
|
|
double t = now_s();
|
|
size_t used = (size_t)snprintf(out, cap,
|
|
"{\"compress\":\"%s\",\"compress_keep\":%d,\"compress_min_bytes\":%d,"
|
|
"\"compress_requests\":%lu,\"compress_bytes_in\":%lu,\"compress_bytes_out\":%lu,"
|
|
"\"endpoints\":[",
|
|
CFG.compress == J_COMPRESS_OFF ? "off" : "tool",
|
|
CFG.compress_keep, CFG.compress_min_bytes,
|
|
g_compress_reqs, g_compress_bytes_in, g_compress_bytes_out);
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
j_endpoint *ep = &CFG.endpoints[i];
|
|
STATE_LOCK();
|
|
char errs[512], hook[512];
|
|
json_escape(ep->last_error, errs, sizeof errs);
|
|
json_escape(ep->last_hook_reason, hook, sizeof hook);
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"%s{\"name\":\"%s\",\"base\":\"%s\",\"kind\":\"%s\",\"context\":%ld,"
|
|
"\"priority\":%d,\"paused\":%s,\"inflight\":%d,\"ok\":%lu,\"fail\":%lu,"
|
|
"\"last_ms\":%ld,\"p95_ms\":%.0f,\"probe_ok\":%d,\"probe_age_s\":%.0f,"
|
|
"\"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,\"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,
|
|
ep->paused ? "true" : "false", ep->inflight, ep->ok_count, ep->fail_count,
|
|
ep->last_ms, lat_p95_ms(ep), ep->probe_ok,
|
|
ep->probe_at > 0 ? t - ep->probe_at : -1.0,
|
|
(int)(ep->offline_until > t ? ep->offline_until - t : 0),
|
|
(int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0),
|
|
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->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);
|
|
STATE_UNLOCK();
|
|
}
|
|
size_t entries = 0, bytes = 0;
|
|
unsigned long hits = 0, misses = 0;
|
|
j_cache_stats(&entries, &bytes, &hits, &misses);
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"],\"usage\":{\"tokens_in\":%lu,\"tokens_out\":%lu,\"tokens_cached\":%lu,"
|
|
"\"cost_usd\":%.6f,\"cost_unknown\":%lu,\"prices\":%d},"
|
|
"\"cache\":{\"ttl_s\":%.0f,\"entries\":%zu,\"bytes\":%zu,\"hits\":%lu,\"misses\":%lu,"
|
|
"\"joined\":%lu,\"deterministic_only\":%s},"
|
|
"\"listener\":{\"tls\":%s},",
|
|
g_tokens_in, g_tokens_out, g_tokens_cached, g_cost_usd, g_cost_unknown,
|
|
j_price_count(),
|
|
CFG.cache_ttl_s, entries, bytes, hits, misses,
|
|
j_cache_flight_joined(), CFG.cache_deterministic_only ? "true" : "false",
|
|
CFG.listen_tls ? "true" : "false");
|
|
pthread_mutex_lock(&SLOTS.mu);
|
|
int inflight = SLOTS.inflight, waiting = SLOTS.waiting;
|
|
pthread_mutex_unlock(&SLOTS.mu);
|
|
double avg_ms = (g_latency_n > 0) ? (g_latency_ms_sum / (double)g_latency_n) : 0.0;
|
|
double eta_s = estimated_wait_s();
|
|
unsigned long mesh_lookups = 0, mesh_hits = 0, mesh_pushes = 0, mesh_errors = 0;
|
|
static const char *mcp_auth_names[] = { "auto", "all", "off" };
|
|
int mcp_auth_mode = (CFG.mcp_auth >= 0 && CFG.mcp_auth <= 2) ? CFG.mcp_auth : 0;
|
|
int mesh_peers = 0;
|
|
j_mesh_stats(&mesh_lookups, &mesh_hits, &mesh_pushes, &mesh_errors, &mesh_peers);
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"\"queue\":{\"inflight\":%d,\"waiting\":%d,\"max_inflight\":%d,\"timeout_s\":%.0f,""\"avg_duration_ms\":%.0f,\"eta_s\":%.0f,\"free_slots\":%d},"
|
|
"\"draining\":%s,\"reuseport\":%s,\"mcp_auth\":\"%s\","
|
|
"\"cache_peers\":{\"peers\":%d,\"lookups\":%lu,\"hits\":%lu,\"pushes\":%lu,"
|
|
"\"errors\":%lu},\"rules\":[",
|
|
inflight, waiting, CFG.max_inflight, CFG.queue_timeout_s,
|
|
avg_ms, eta_s, (CFG.max_inflight - inflight > 0 ? CFG.max_inflight - inflight : 0),
|
|
g_draining ? "true" : "false", CFG.so_reuseport ? "true" : "false",
|
|
mcp_auth_names[mcp_auth_mode],
|
|
mesh_peers, mesh_lookups, mesh_hits, mesh_pushes, mesh_errors);
|
|
for (int i = 0; i < CFG.rule_count; i++) {
|
|
j_rule *r = &CFG.rules[i];
|
|
/* all targets, each with the model it is asked for ("ep" or "ep as M") */
|
|
char chain[1024] = "";
|
|
size_t cu = 0;
|
|
for (int tgt = 0; tgt < r->target_count && cu < sizeof chain - 1; tgt++) {
|
|
int wrote = snprintf(chain + cu, sizeof chain - cu, "%s%s%s%s",
|
|
tgt ? ", " : "", r->targets[tgt],
|
|
r->target_as[tgt][0] ? " as " : "",
|
|
r->target_as[tgt]);
|
|
if (wrote < 0) break;
|
|
cu += (size_t)wrote;
|
|
}
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"need_min\":%ld,"
|
|
"\"need_max\":%ld,\"ctx_min\":%ld,\"ctx_max\":%ld,\"vision\":%d,"
|
|
"\"targets\":\"%s\"}",
|
|
i ? "," : "", r->line, r->model_glob, r->path_glob,
|
|
r->block ? "true" : "false", r->need_min, r->need_max,
|
|
r->ctx_min, r->ctx_max, r->vision, chain);
|
|
}
|
|
used += (size_t)snprintf(out + used, cap - used, "],");
|
|
/* MCP: welche Server angebunden sind, wie viele Werkzeuge sie liefern und
|
|
* was zuletzt schiefging. Das Dashboard zeigt genau diese Zahlen. */
|
|
{
|
|
char mcpjson[8192];
|
|
int n = j_mcp_status_json(&CFG, mcpjson, sizeof mcpjson);
|
|
used += (size_t)snprintf(out + used, cap - used, "\"mcp\":%.*s,", n > 0 ? n : 2,
|
|
n > 0 ? mcpjson : "[]");
|
|
}
|
|
/* Die Schlüssel selbst: Name, Modell-Glob, Ziele und was sie verbraucht haben.
|
|
* Der Token steht hier nie — er liegt in der Umgebung, nicht im Bericht. */
|
|
used += (size_t)snprintf(out + used, cap - used, "\"vkeys\":[");
|
|
for (int i = 0; i < CFG.vkey_count; i++) {
|
|
j_vkey *v = &CFG.vkeys[i];
|
|
char en[J_NAME_MAX], ea[J_GLOB_MAX], ee[J_URL_MAX];
|
|
json_escape(v->name, en, sizeof en);
|
|
json_escape(v->allow, ea, sizeof ea);
|
|
json_escape(v->endpoints, ee, sizeof ee);
|
|
STATE_LOCK();
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"%s{\"name\":\"%s\",\"allow\":\"%s\",\"endpoints\":\"%s\","
|
|
"\"rpm\":%d,\"budget_usd\":%.4f,\"spent_usd\":%.6f,"
|
|
"\"hits\":%lu,\"denied\":%lu,\"window_hits\":%d}",
|
|
i ? "," : "", en, ea, ee, v->rpm, v->budget_usd, v->spent_usd,
|
|
v->hits, v->denied, v->window_hits);
|
|
STATE_UNLOCK();
|
|
}
|
|
used += (size_t)snprintf(out + used, cap - used, "],");
|
|
used += (size_t)snprintf(out + used, cap - used,
|
|
"\"requests\":{\"ok\":%lu,\"fail\":%lu},"
|
|
"\"retries\":{\"count\":%lu,\"num\":%d,\"backoff_s\":%.2f,\"max_wait_s\":%.0f},"
|
|
"\"offline_waits\":%lu,\"offline_wait_s\":%.0f,\"guard_refused\":%lu,"
|
|
"\"traffic\":{\"request_bytes\":%lu,\"response_bytes\":%lu},"
|
|
"\"latency\":{\"avg_ms\":%.1f,\"samples\":%lu},"
|
|
"\"uptime_s\":%.0f}",
|
|
g_req_ok, g_req_fail, g_retries, CFG.retry_num, CFG.retry_backoff_s,
|
|
CFG.retry_max_wait_s,
|
|
g_offline_waits, CFG.offline_wait_s, g_guard_refused,
|
|
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;
|
|
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;
|
|
}
|
|
|
|
/* Retry-After ist entweder eine Zahl (Sekunden) oder ein HTTP-Datum. Beides wird
|
|
* gelesen — das Datum über days_from_civil statt timegm, weil timegm nicht POSIX ist und
|
|
* die Zeitzone hier ohnehin keine Rolle spielt: die Angabe ist immer GMT. Alles, was
|
|
* weder Zahl noch lesbares Datum ist, ergibt 0 ("keine Auskunft"), nicht eine geratene
|
|
* Zahl. */
|
|
static int retry_after_seconds(const char *v)
|
|
{
|
|
if (!v || !*v) return 0;
|
|
if (v[0] >= '0' && v[0] <= '9') {
|
|
long n = strtol(v, NULL, 10);
|
|
if (n < 0) return 0;
|
|
if (n > 86400) n = 86400;
|
|
return (int)n;
|
|
}
|
|
/* IMF-fixdate, die einzige Form, die RFC 7231 dafür vorsieht:
|
|
* Sun, 06 Nov 1994 08:49:37 GMT */
|
|
static const char *mon_names[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
|
|
char wd[8] = "", mon[8] = "";
|
|
int d = 0, y = 0, hh = 0, mm = 0, ss = 0;
|
|
if (sscanf(v, "%7[^,], %2d %3s %4d %2d:%2d:%2d", wd, &d, mon, &y, &hh, &mm, &ss) != 7)
|
|
return 0;
|
|
int m = 0;
|
|
for (int i = 0; i < 12; i++)
|
|
if (!strcasecmp(mon, mon_names[i])) { m = i + 1; break; }
|
|
if (!m || d < 1 || d > 31 || y < 1970 || hh > 23 || mm > 59 || ss > 60) return 0;
|
|
long epoch = days_from_civil(y, (unsigned)m, (unsigned)d) * 86400L +
|
|
(long)hh * 3600L + (long)mm * 60L + (long)ss;
|
|
long diff = epoch - (long)time(NULL);
|
|
if (diff <= 0) return 0; /* Zeitpunkt vorbei: sofort weiterversuchen */
|
|
if (diff > 86400) diff = 86400;
|
|
return (int)diff;
|
|
}
|
|
|
|
#define SPEND_MAX_KEYS 32
|
|
#define SPEND_MAX_MODELS 64
|
|
|
|
typedef struct {
|
|
char name[J_GLOB_MAX];
|
|
double cost;
|
|
unsigned long n;
|
|
} spend_row;
|
|
|
|
/* 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)
|
|
{
|
|
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 = 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 && CFG.spend_log[0] && 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) {
|
|
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) { *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\":[",
|
|
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, "]}");
|
|
*len_out = u;
|
|
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)
|
|
{
|
|
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;
|
|
char *out = build_status(&len);
|
|
if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; }
|
|
send_simple(c, 200, "OK", out);
|
|
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);
|
|
unsigned long m_lookups = 0, m_hits = 0, m_pushes = 0, m_errors = 0;
|
|
int m_peers = 0;
|
|
j_mesh_stats(&m_lookups, &m_hits, &m_pushes, &m_errors, &m_peers);
|
|
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 + (size_t)CFG.vkey_count * 320;
|
|
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_offline_waits_total Requests that waited for the chain to come back.\n"
|
|
"# TYPE junction_offline_waits_total counter\n"
|
|
"junction_offline_waits_total %lu\n"
|
|
"# HELP junction_guard_refused_total Requests the guard script refused.\n"
|
|
"# TYPE junction_guard_refused_total counter\n"
|
|
"junction_guard_refused_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_cache_peer_lookups_total counter\n"
|
|
"junction_cache_peer_lookups_total %lu\n"
|
|
"# TYPE junction_cache_peer_hits_total counter\n"
|
|
"junction_cache_peer_hits_total %lu\n"
|
|
"# TYPE junction_cache_peer_pushes_total counter\n"
|
|
"junction_cache_peer_pushes_total %lu\n"
|
|
"# TYPE junction_cache_peer_errors_total counter\n"
|
|
"junction_cache_peer_errors_total %lu\n"
|
|
"# TYPE junction_cache_peers gauge\n"
|
|
"junction_cache_peers %d\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"
|
|
"# TYPE junction_draining gauge\n"
|
|
"junction_draining %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_offline_waits, g_guard_refused,
|
|
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(),
|
|
m_lookups, m_hits, m_pushes, m_errors, m_peers,
|
|
inflight, waiting, CFG.max_inflight, g_draining ? 1 : 0,
|
|
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"
|
|
"# HELP junction_endpoint_latency_seconds Latency of served requests, as a histogram:\n"
|
|
"# an average hides exactly the requests that hurt.\n"
|
|
"# TYPE junction_endpoint_latency_seconds histogram\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);
|
|
/* Das Histogramm in kumulativer Form, wie Prometheus es verlangt: der Eimer
|
|
* "le=1" enthält auch alles, was schneller war. */
|
|
unsigned long cum = 0;
|
|
char lb[2048];
|
|
size_t lu = 0;
|
|
for (int b = 0; b <= J_LAT_BUCKETS; b++) {
|
|
cum += ep->lat_bucket[b];
|
|
if (b < J_LAT_BUCKETS)
|
|
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
|
|
"junction_endpoint_latency_seconds_bucket{endpoint=\"%s\",le=\"%g\"} %lu\n",
|
|
ep->name, g_lat_bounds[b], cum);
|
|
else
|
|
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
|
|
"junction_endpoint_latency_seconds_bucket{endpoint=\"%s\",le=\"+Inf\"} %lu\n",
|
|
ep->name, cum);
|
|
}
|
|
lu += (size_t)snprintf(lb + lu, sizeof lb - lu,
|
|
"junction_endpoint_latency_seconds_sum{endpoint=\"%s\"} %.3f\n"
|
|
"junction_endpoint_latency_seconds_count{endpoint=\"%s\"} %lu\n",
|
|
ep->name, ep->lat_sum_s, ep->name, ep->lat_n);
|
|
STATE_UNLOCK();
|
|
met(out, cap, &u, "%s", lb);
|
|
}
|
|
|
|
/* Je virtuellem Schlüssel: Anfragen, Ablehnungen, Verbrauch im Monat. Damit lässt
|
|
* sich ein Limit sehen, bevor es zuschlägt. */
|
|
if (CFG.vkey_count > 0) {
|
|
met(out, cap, &u,
|
|
"# HELP junction_vkey_requests_total Requests per virtual key.\n"
|
|
"# TYPE junction_vkey_requests_total counter\n"
|
|
"# HELP junction_vkey_spend_usd_total Spend of this calendar month per virtual key.\n"
|
|
"# TYPE junction_vkey_spend_usd_total counter\n"
|
|
"# HELP junction_vkey_budget_usd Monthly budget of a virtual key (0 = none).\n"
|
|
"# TYPE junction_vkey_budget_usd gauge\n"
|
|
"# HELP junction_vkey_rpm Request limit per minute (0 = none).\n"
|
|
"# TYPE junction_vkey_rpm gauge\n");
|
|
for (int i = 0; i < CFG.vkey_count; i++) {
|
|
j_vkey *v = &CFG.vkeys[i];
|
|
STATE_LOCK();
|
|
met(out, cap, &u,
|
|
"junction_vkey_requests_total{vkey=\"%s\",outcome=\"ok\"} %lu\n"
|
|
"junction_vkey_requests_total{vkey=\"%s\",outcome=\"denied\"} %lu\n"
|
|
"junction_vkey_spend_usd_total{vkey=\"%s\"} %.6f\n"
|
|
"junction_vkey_budget_usd{vkey=\"%s\"} %.4f\n"
|
|
"junction_vkey_rpm{vkey=\"%s\"} %d\n",
|
|
v->name, v->hits, v->name, v->denied, v->name, v->spent_usd,
|
|
v->name, v->budget_usd, v->name, v->rpm);
|
|
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
|
|
* weiterläuft. Laufende Anfragen behalten ihre Kopie bis zum Ende. */
|
|
void j_config_swap(j_config *fresh)
|
|
{
|
|
pthread_rwlock_wrlock(&g_rules_rw);
|
|
STATE_LOCK();
|
|
CFG.endpoint_count = fresh->endpoint_count;
|
|
memcpy(CFG.endpoints, fresh->endpoints, sizeof CFG.endpoints);
|
|
CFG.rule_count = fresh->rule_count;
|
|
memcpy(CFG.rules, fresh->rules, sizeof CFG.rules);
|
|
CFG.mcp_count = fresh->mcp_count;
|
|
memcpy(CFG.mcps, fresh->mcps, sizeof CFG.mcps);
|
|
CFG.mcp_cache_ttl_s = fresh->mcp_cache_ttl_s;
|
|
/* Laufzeit der Schlüssel über den Tausch retten: Verbrauch und Fenster sind
|
|
* Buchführung, keine Konfiguration. Ohne das setzte ein config.set mitten im
|
|
* Monat jedes Budget auf null zurück — die Sperre wäre mit einem Klick weg. */
|
|
int old_vkeys = CFG.vkey_count;
|
|
for (int i = 0; i < fresh->vkey_count; i++) {
|
|
for (int j = 0; j < old_vkeys; j++) {
|
|
if (strcmp(fresh->vkeys[i].name, CFG.vkeys[j].name)) continue;
|
|
fresh->vkeys[i].spent_usd = CFG.vkeys[j].spent_usd;
|
|
fresh->vkeys[i].hits = CFG.vkeys[j].hits;
|
|
fresh->vkeys[i].denied = CFG.vkeys[j].denied;
|
|
fresh->vkeys[i].window_start = CFG.vkeys[j].window_start;
|
|
fresh->vkeys[i].window_hits = CFG.vkeys[j].window_hits;
|
|
break;
|
|
}
|
|
}
|
|
CFG.vkey_count = fresh->vkey_count;
|
|
memcpy(CFG.vkeys, fresh->vkeys, sizeof CFG.vkeys);
|
|
CFG.pool_count = fresh->pool_count;
|
|
memcpy(CFG.pools, fresh->pools, sizeof CFG.pools);
|
|
snprintf(CFG.ctx_fallback, sizeof CFG.ctx_fallback, "%s", fresh->ctx_fallback);
|
|
snprintf(CFG.ctx_fallback_model, sizeof CFG.ctx_fallback_model, "%s",
|
|
fresh->ctx_fallback_model);
|
|
CFG.balance = fresh->balance;
|
|
snprintf(CFG.spend_log, sizeof CFG.spend_log, "%s", fresh->spend_log);
|
|
snprintf(CFG.guard_cmd, sizeof CFG.guard_cmd, "%s", fresh->guard_cmd);
|
|
CFG.retry_num = fresh->retry_num;
|
|
CFG.retry_backoff_s = fresh->retry_backoff_s;
|
|
CFG.offline_wait_s = fresh->offline_wait_s;
|
|
CFG.compress = fresh->compress;
|
|
CFG.compress_keep = fresh->compress_keep;
|
|
CFG.compress_min_bytes = fresh->compress_min_bytes;
|
|
CFG.model_allow_count = fresh->model_allow_count;
|
|
memcpy(CFG.model_allow, fresh->model_allow, sizeof CFG.model_allow);
|
|
CFG.model_deny_count = fresh->model_deny_count;
|
|
memcpy(CFG.model_deny, fresh->model_deny, sizeof CFG.model_deny);
|
|
STATE_UNLOCK();
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
jlog("config_applied", "endpoints=%d rules=%d mcps=%d",
|
|
CFG.endpoint_count, CFG.rule_count, CFG.mcp_count);
|
|
}
|
|
|
|
/* ------------------------------------------------------- Steuerkanalschnittstelle */
|
|
|
|
/* Der Statusbericht, den auch /status ausliefert. */
|
|
char *j_status_json(size_t *len)
|
|
{
|
|
return build_status(len);
|
|
}
|
|
|
|
void j_rules_write_lock(void)
|
|
{
|
|
pthread_rwlock_wrlock(&g_rules_rw);
|
|
}
|
|
|
|
void j_rules_write_unlock(void)
|
|
{
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
}
|
|
|
|
void j_set_endpoint_paused(const char *name, int pause, char *err, size_t errlen)
|
|
{
|
|
STATE_LOCK();
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
if (!strcmp(CFG.endpoints[i].name, name)) {
|
|
CFG.endpoints[i].paused = pause;
|
|
CFG.endpoints[i].cooldown_until = 0;
|
|
if (!pause)
|
|
CFG.endpoints[i].offline_until = 0;
|
|
STATE_UNLOCK();
|
|
jlog(pause ? "pause" : "resume", "endpoint=%s via=control", name);
|
|
return;
|
|
}
|
|
}
|
|
STATE_UNLOCK();
|
|
snprintf(err, errlen, "no such endpoint: %s", name);
|
|
}
|
|
|
|
/* Eine Regel setzen: gleicher Name (die Zeile) wird ersetzt, sonst angehängt.
|
|
* Geschrieben wird unter Schreibsperre, weil Anfragen gleichzeitig unter
|
|
* Lesesperre nach passenden Regeln suchen. */
|
|
int j_rule_apply(const char *text, char *err, size_t errlen)
|
|
{
|
|
j_rule fresh;
|
|
int count;
|
|
|
|
if (j_config_rule_from_line(text, &fresh, err, errlen) != 0)
|
|
return -1;
|
|
|
|
pthread_rwlock_wrlock(&g_rules_rw);
|
|
/* Ersetzen, wenn eine Regel mit derselben model/path-Kombination existiert —
|
|
* sonst stünden zwei Regeln nebeneinander und die erste gewinnt. */
|
|
int replaced = 0;
|
|
for (int i = 0; i < CFG.rule_count; i++) {
|
|
if (!strcmp(CFG.rules[i].model_glob, fresh.model_glob) &&
|
|
!strcmp(CFG.rules[i].path_glob, fresh.path_glob)) {
|
|
fresh.line = CFG.rules[i].line;
|
|
CFG.rules[i] = fresh;
|
|
replaced = 1;
|
|
break;
|
|
}
|
|
}
|
|
if (!replaced) {
|
|
if (CFG.rule_count >= J_MAX_RULES) {
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
snprintf(err, errlen, "more than %d rules", J_MAX_RULES);
|
|
return -1;
|
|
}
|
|
CFG.rules[CFG.rule_count] = fresh;
|
|
CFG.rules[CFG.rule_count].line = CFG.rule_count + 1;
|
|
CFG.rule_count++;
|
|
}
|
|
count = CFG.rule_count;
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
jlog("rule_set", "rules=%d replaced=%d", count, replaced);
|
|
return 0;
|
|
}
|
|
|
|
/* Regel löschen: per Name ("model" oder "model -> path") oder per Nummer. */
|
|
int j_rule_remove(const char *name, int index, char *err, size_t errlen)
|
|
{
|
|
int victim = -1;
|
|
|
|
pthread_rwlock_wrlock(&g_rules_rw);
|
|
if (index >= 0) {
|
|
if (index < CFG.rule_count)
|
|
victim = index;
|
|
} else if (name && name[0]) {
|
|
for (int i = 0; i < CFG.rule_count; i++) {
|
|
if (!strcmp(CFG.rules[i].model_glob, name) ||
|
|
!strcmp(CFG.rules[i].path_glob, name)) {
|
|
victim = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (victim < 0) {
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
snprintf(err, errlen, "no such rule: %s", name && name[0] ? name : "(index)");
|
|
return -1;
|
|
}
|
|
for (int i = victim; i + 1 < CFG.rule_count; i++)
|
|
CFG.rules[i] = CFG.rules[i + 1];
|
|
CFG.rule_count--;
|
|
int left = CFG.rule_count;
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
jlog("rule_delete", "removed=%d rules=%d", victim, left);
|
|
return 0;
|
|
}
|
|
|
|
static void admin(j_conn *c, const char *path)
|
|
{
|
|
const char *p = path + strlen("/admin/");
|
|
const char *slash = strchr(p, '/');
|
|
char action[16], name[J_NAME_MAX];
|
|
if (!slash) {
|
|
send_simple(c, 400, "Bad Request", "{\"error\":\"use /admin/pause|resume/<name>\"}");
|
|
return;
|
|
}
|
|
snprintf(action, sizeof action, "%.*s", (int)(slash - p), p);
|
|
snprintf(name, sizeof name, "%s", slash + 1);
|
|
|
|
if (!strcmp(action, "flush") && !strcmp(name, "cache")) {
|
|
j_cache_clear();
|
|
send_simple(c, 200, "OK", "{\"cache\":\"flushed\"}");
|
|
return;
|
|
}
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
j_endpoint *ep = &CFG.endpoints[i];
|
|
if (strcmp(ep->name, name)) continue;
|
|
if (!strcmp(action, "pause")) ep->paused = 1;
|
|
else if (!strcmp(action, "resume")) {
|
|
ep->paused = 0;
|
|
ep->offline_until = 0;
|
|
ep->cooldown_until = 0;
|
|
} else {
|
|
send_simple(c, 400, "Bad Request", "{\"error\":\"use pause or resume\"}");
|
|
return;
|
|
}
|
|
jlog("admin", "endpoint=%s action=%s paused=%d", name, action, ep->paused);
|
|
char body[160];
|
|
snprintf(body, sizeof body, "{\"name\":\"%s\",\"paused\":%s}", name,
|
|
ep->paused ? "true" : "false");
|
|
send_simple(c, 200, "OK", body);
|
|
return;
|
|
}
|
|
send_simple(c, 404, "Not Found", "{\"error\":\"unknown endpoint\"}");
|
|
}
|
|
|
|
/* Führt ein Kommando aus und gibt dessen getrimmte Standardausgabe zurück.
|
|
*
|
|
* Gebraucht für base_cmd und pass_cmd: opencode serve bindet einen freien Port und
|
|
* erzeugt bei jedem Start ein neues Passwort, beides ist nur über ein Kommando zu
|
|
* erfahren. Ein Cache von 60 Sekunden verhindert, dass jede Anfrage einen Prozess
|
|
* startet — häufiger als einmal pro Minute ändert sich daran nichts.
|
|
*/
|
|
static int cmd_value(int ep_index, int which, char *out, size_t outlen)
|
|
{
|
|
static char cache_base[J_MAX_ENDPOINTS][J_URL_MAX];
|
|
static char cache_pass[J_MAX_ENDPOINTS][J_NAME_MAX];
|
|
static double cache_at[J_MAX_ENDPOINTS][2];
|
|
double now = now_s();
|
|
char *dst = which ? cache_pass[ep_index] : cache_base[ep_index];
|
|
size_t dstlen = which ? J_NAME_MAX : J_URL_MAX;
|
|
|
|
if (cache_at[ep_index][which] > 0 && now - cache_at[ep_index][which] < 60.0 && dst[0]) {
|
|
snprintf(out, outlen, "%s", dst);
|
|
return 0;
|
|
}
|
|
const char *cmd = which ? CFG.endpoints[ep_index].pass_cmd : CFG.endpoints[ep_index].base_cmd;
|
|
FILE *f = popen(cmd, "r");
|
|
if (!f) return -1;
|
|
char line[1024] = "";
|
|
size_t got = fread(line, 1, sizeof line - 1, f);
|
|
line[got] = '\0';
|
|
pclose(f);
|
|
/* erste nicht-leere Zeile, getrimmt */
|
|
char *p = line;
|
|
while (*p && isspace((unsigned char)*p)) p++;
|
|
char *nl = p;
|
|
while (*nl && *nl != '\n' && *nl != '\r') nl++;
|
|
*nl = '\0';
|
|
if (!*p) return -1;
|
|
snprintf(dst, dstlen, "%s", p);
|
|
cache_at[ep_index][which] = now;
|
|
snprintf(out, outlen, "%s", p);
|
|
return 0;
|
|
}
|
|
|
|
/* Bedient einen Endpunkt, der nicht OpenAI spricht, sondern opencode serve.
|
|
* Gibt 0 zurück, wenn die Antwort an den Client geschrieben wurde. */
|
|
static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_req *rq,
|
|
const char *model, char *err, size_t errlen)
|
|
{
|
|
(void)ep_index_owner;
|
|
char base[J_URL_MAX], pass[J_NAME_MAX];
|
|
if (cmd_value((int)(ep_index_owner - CFG.endpoints), 0, base, sizeof base) != 0) {
|
|
if (CFG.endpoints[ep_index_owner - CFG.endpoints].base_cmd[0]) {
|
|
snprintf(err, errlen, "opencode: base_cmd failed");
|
|
return -1;
|
|
}
|
|
snprintf(base, sizeof base, "%s", ep_index_owner->base);
|
|
}
|
|
pass[0] = '\0';
|
|
if (ep_index_owner->pass_cmd[0] &&
|
|
cmd_value((int)(ep_index_owner - CFG.endpoints), 1, pass, sizeof pass) != 0) {
|
|
snprintf(err, errlen, "opencode: pass_cmd failed");
|
|
return -1;
|
|
}
|
|
|
|
char *body = NULL;
|
|
size_t blen = 0;
|
|
int rc;
|
|
if (!strncmp(rq->path, "/v1/models", 10)) {
|
|
rc = j_opencode_models(base, ep_index_owner->auth_basic_user, pass, &body, &blen,
|
|
ep_index_owner->timeout_s, err, errlen);
|
|
if (rc == 0 && body) {
|
|
/* Dieselbe Modell-Politik wie auf dem OpenAI-Pfad: die Brücke liefert
|
|
* eine Liste, die erst gefiltert und dann um virtuelle Alias-Modelle
|
|
* ergänzt wird. */
|
|
char *filtered = NULL;
|
|
size_t filtered_len = 0;
|
|
if (j_models_filter_list(body, blen, &filtered, &filtered_len) == 0 && filtered) {
|
|
free(body);
|
|
body = filtered;
|
|
blen = filtered_len;
|
|
}
|
|
char *patched = NULL;
|
|
size_t patched_len = 0;
|
|
if (j_models_patch_list(body, blen, &patched, &patched_len) == 0 && patched) {
|
|
free(body);
|
|
body = patched;
|
|
blen = patched_len;
|
|
}
|
|
}
|
|
} else {
|
|
rc = j_opencode_chat(base, ep_index_owner->auth_basic_user, pass, model, rq->body,
|
|
&body, &blen, ep_index_owner->timeout_s, err, errlen);
|
|
}
|
|
if (rc != 0) return -1;
|
|
|
|
send_simple(client, 200, "OK", body);
|
|
free(body);
|
|
return 0;
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- rules */
|
|
static int rule_matches(const j_rule *r, const char *path, const char *model, long need,
|
|
long ctx, int has_image)
|
|
{
|
|
if (r->model_glob[0] && fnmatch(r->model_glob, model ? model : "", 0) != 0) return 0;
|
|
if (r->path_glob[0] && fnmatch(r->path_glob, path, 0) != 0) return 0;
|
|
if (r->need_min >= 0 && need < r->need_min) return 0;
|
|
if (r->need_max >= 0 && need > r->need_max) return 0;
|
|
/* ctx: ohne Schätzung (-1) erfüllt keine ctx-Bedingung — was man nicht messen
|
|
* kann, wird nicht angenommen. */
|
|
if (r->ctx_min >= 0 && ctx < r->ctx_min) return 0;
|
|
if (r->ctx_max >= 0 && ctx > r->ctx_max) return 0;
|
|
if (r->vision == 1 && !has_image) return 0;
|
|
if (r->vision == 0 && has_image) return 0;
|
|
return 1;
|
|
}
|
|
|
|
static int first_matching_rule(const char *path, const char *model, long need,
|
|
long ctx, int has_image, j_rule *out)
|
|
{
|
|
int found = 0;
|
|
|
|
pthread_rwlock_rdlock(&g_rules_rw);
|
|
for (int i = 0; i < CFG.rule_count; i++) {
|
|
if (rule_matches(&CFG.rules[i], path, model, need, ctx, has_image)) {
|
|
*out = CFG.rules[i];
|
|
found = 1;
|
|
break;
|
|
}
|
|
}
|
|
pthread_rwlock_unlock(&g_rules_rw);
|
|
return found;
|
|
}
|
|
|
|
static const j_pool *find_pool(const char *name)
|
|
{
|
|
if (!name || !name[0]) return NULL;
|
|
for (int i = 0; i < CFG.pool_count; i++)
|
|
if (!strcmp(CFG.pools[i].name, name)) return &CFG.pools[i];
|
|
return NULL;
|
|
}
|
|
|
|
static char *rewrite_model(const char *body, const char *new_model)
|
|
{
|
|
if (!body) return NULL;
|
|
const char *key = strstr(body, "\"model\"");
|
|
if (!key) return NULL;
|
|
const char *v = key + 7;
|
|
while (*v && (*v == ':' || isspace((unsigned char)*v))) v++;
|
|
if (*v != '"') return NULL;
|
|
const char *start = v + 1;
|
|
const char *end = start;
|
|
while (*end && *end != '"') { if (*end == '\\' && end[1]) end++; end++; }
|
|
if (*end != '"') return NULL;
|
|
|
|
size_t pre = (size_t)(start - body);
|
|
/* `end` points AT the closing quote — copying from end + 1 dropped it and sent
|
|
* the endpoint a body that was no longer valid JSON. */
|
|
size_t post = strlen(end);
|
|
size_t nl = strlen(new_model);
|
|
char *out = malloc(pre + nl + post + 1);
|
|
if (!out) return NULL;
|
|
memcpy(out, body, pre);
|
|
memcpy(out + pre, new_model, nl);
|
|
memcpy(out + pre + nl, end, post + 1);
|
|
return out;
|
|
}
|
|
|
|
/* A rule's target model may be plain; the client's effort selector still has to
|
|
* survive the rewrite. An explicit "#..." in the target wins. */
|
|
static void model_for_target(const char *target, const char *orig,
|
|
char *out, size_t outlen)
|
|
{
|
|
/* "#max" is an effort suffix on the model the client asked for. */
|
|
if (target[0] == '#') {
|
|
const char *hash = orig ? strchr(orig, '#') : NULL;
|
|
size_t n = hash ? (size_t)(hash - orig) : (orig ? strlen(orig) : 0);
|
|
if (n >= outlen) n = outlen - 1;
|
|
if (n > 0) memcpy(out, orig, n);
|
|
out[n] = '\0';
|
|
snprintf(out + n, outlen - n, "%s", target);
|
|
return;
|
|
}
|
|
snprintf(out, outlen, "%s", target);
|
|
if (strchr(out, '#') != NULL) return;
|
|
const char *hash = orig ? strrchr(orig, '#') : NULL;
|
|
if (hash && hash[1]) {
|
|
size_t n = strlen(out);
|
|
if (n < outlen - 1)
|
|
snprintf(out + n, outlen - n, "%s", hash);
|
|
}
|
|
}
|
|
|
|
/* ------------------------------------------------------------------- network */
|
|
static int split_url(const char *base, char *host, size_t hostlen, char *port,
|
|
size_t portlen, char *prefix, size_t prefixlen, int *is_tls)
|
|
{
|
|
const char *p = base;
|
|
*is_tls = 0;
|
|
if (!strncmp(p, "https://", 8)) { *is_tls = 1; p += 8; }
|
|
else if (!strncmp(p, "http://", 7)) p += 7;
|
|
else return -1;
|
|
const char *slash = strchr(p, '/');
|
|
const char *hend = slash ? slash : p + strlen(p);
|
|
const char *colon = memchr(p, ':', (size_t)(hend - p));
|
|
size_t hl = colon ? (size_t)(colon - p) : (size_t)(hend - p);
|
|
if (hl >= hostlen) return -1;
|
|
memcpy(host, p, hl);
|
|
host[hl] = '\0';
|
|
if (colon) {
|
|
size_t pl = (size_t)(hend - colon - 1);
|
|
if (pl >= portlen) return -1;
|
|
memcpy(port, colon + 1, pl);
|
|
port[pl] = '\0';
|
|
} else {
|
|
snprintf(port, portlen, "%s", *is_tls ? "443" : "80");
|
|
}
|
|
snprintf(prefix, prefixlen, "%s", slash ? slash : "");
|
|
size_t pl2 = strlen(prefix);
|
|
while (pl2 > 1 && prefix[pl2 - 1] == '/') prefix[--pl2] = '\0';
|
|
return 0;
|
|
}
|
|
|
|
/* Connectivity is decided by the request itself: a second "probe" connection per
|
|
* request doubles the cost and wedges servers that serve one connection at a time
|
|
* (the probe takes the slot, closes without a request, and the real one waits). A
|
|
* connect/handshake failure is classified as "offline" below. */
|
|
static int error_is_offline(const char *err)
|
|
{
|
|
return !strncmp(err, "connect", 7) || !strncmp(err, "resolve", 7) ||
|
|
!strncmp(err, "tls handshake", 13) || !strncmp(err, "tls_verify", 10);
|
|
}
|
|
|
|
/* ---------------------------------------------------------------------- hooks */
|
|
static int run_cmd(const char *cmd, const j_endpoint *ep, const char *path,
|
|
const char *model, long need, int attempt, char *reason, size_t rlen)
|
|
{
|
|
int out[2];
|
|
if (pipe(out)) return -1;
|
|
pid_t pid = fork();
|
|
if (pid < 0) { close(out[0]); close(out[1]); return -1; }
|
|
if (pid == 0) {
|
|
dup2(out[1], STDOUT_FILENO);
|
|
dup2(out[1], STDERR_FILENO);
|
|
close(out[0]);
|
|
close(out[1]);
|
|
char buf[64];
|
|
setenv("JUNCTION_BACKEND", ep->name, 1);
|
|
setenv("JUNCTION_BASE", ep->base, 1);
|
|
setenv("JUNCTION_PATH", path, 1);
|
|
setenv("JUNCTION_MODEL", model, 1);
|
|
snprintf(buf, sizeof buf, "%ld", need);
|
|
setenv("JUNCTION_NEED_TOKENS", buf, 1);
|
|
snprintf(buf, sizeof buf, "%d", attempt);
|
|
setenv("JUNCTION_ATTEMPT", buf, 1);
|
|
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
|
|
_exit(127);
|
|
}
|
|
close(out[1]);
|
|
if (rlen) reason[0] = '\0';
|
|
size_t used = 0;
|
|
double deadline = now_s() + 60.0;
|
|
int status = 0, timed_out = 0;
|
|
for (;;) {
|
|
if (now_s() >= deadline) { kill(pid, SIGKILL); timed_out = 1; break; }
|
|
struct pollfd p = { .fd = out[0], .events = POLLIN, .revents = 0 };
|
|
if (poll(&p, 1, 200) > 0 && (p.revents & POLLIN)) {
|
|
char tmp[256];
|
|
ssize_t n = read(out[0], tmp, sizeof tmp);
|
|
if (n > 0 && used < rlen - 1) {
|
|
size_t take = (size_t)n;
|
|
if (take > rlen - 1 - used) take = rlen - 1 - used;
|
|
memcpy(reason + used, tmp, take);
|
|
used += take;
|
|
reason[used] = '\0';
|
|
}
|
|
}
|
|
if (waitpid(pid, &status, WNOHANG) == pid) break;
|
|
}
|
|
close(out[0]);
|
|
if (timed_out) {
|
|
waitpid(pid, &status, 0);
|
|
if (rlen) snprintf(reason, rlen, "hook_timeout");
|
|
return 1;
|
|
}
|
|
if (rlen) {
|
|
reason[strcspn(reason, "\r\n")] = '\0';
|
|
if (!reason[0] && WIFEXITED(status))
|
|
snprintf(reason, rlen, "hook_exit_%d", WEXITSTATUS(status));
|
|
}
|
|
return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 0 : 1;
|
|
}
|
|
|
|
|
|
/* ------------------------------------------------------------------ budgets */
|
|
static int ep_in_offpeak(const j_endpoint *ep);
|
|
/* The endpoint's usage_cmd prints one line of key=value pairs. Junction does not
|
|
* speak HTTP to a usage API itself: fetching (TLS, headers, JSON) belongs in a
|
|
* script, the policy belongs here. A command that fails leaves the last value in
|
|
* place and marks usage_ok = 0, so "unknown" never reads as "free". */
|
|
static void usage_parse(j_endpoint *ep, const char *text)
|
|
{
|
|
int seen = 0;
|
|
const char *p = text;
|
|
while (p && *p) {
|
|
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ';') p++;
|
|
const char *k = p;
|
|
while (*p && *p != '=' && *p != ' ' && *p != '\n') p++;
|
|
if (*p != '=') { while (*p && *p != ' ' && *p != '\n') p++; continue; }
|
|
size_t klen = (size_t)(p - k);
|
|
p++;
|
|
const char *v = p;
|
|
while (*p && *p != ' ' && *p != '\n' && *p != ';') p++;
|
|
char tmp[64];
|
|
size_t vlen = (size_t)(p - v);
|
|
if (vlen >= sizeof tmp) vlen = sizeof tmp - 1;
|
|
memcpy(tmp, v, vlen);
|
|
tmp[vlen] = '\0';
|
|
double d = strtod(tmp, NULL);
|
|
if (klen == 7 && !strncmp(k, "percent", 7)) { ep->usage_percent = d; seen = 1; }
|
|
else if (klen == 8 && !strncmp(k, "used_usd", 8)) { ep->usage_used_usd = d; seen = 1; }
|
|
else if (klen == 10 && !strncmp(k, "budget_usd", 10)) { ep->usage_budget_usd = d; seen = 1; }
|
|
else if (klen == 7 && !strncmp(k, "reset_s", 7)) { ep->usage_reset_s = d; seen = 1; }
|
|
}
|
|
ep->usage_ok = seen;
|
|
ep->offpeak_active = ep_in_offpeak(ep);
|
|
/* A window that has reset makes the endpoint usable again without a restart. */
|
|
if (seen && ep->usage_reset_s > 0 && now_s() >= ep->usage_reset_s) ep->exhausted = 0;
|
|
if (seen && ep->budget_hard > 0 && ep->usage_percent >= ep->budget_hard && ep->on_hard_skip)
|
|
ep->exhausted = 1;
|
|
}
|
|
|
|
static void *usage_thread(void *arg)
|
|
{
|
|
(void)arg;
|
|
for (;;) {
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
j_endpoint *ep = &CFG.endpoints[i];
|
|
if (!ep->usage_cmd[0] || ep->usage_poll_s <= 0) continue;
|
|
double now = now_s();
|
|
if (ep->usage_at > 0 && now - ep->usage_at < ep->usage_poll_s) continue;
|
|
char out[512] = "";
|
|
int rc = run_cmd(ep->usage_cmd, ep, "", "", -1, 0, out, sizeof out);
|
|
STATE_LOCK();
|
|
if (rc == 0) usage_parse(ep, out);
|
|
else ep->usage_ok = 0;
|
|
ep->usage_at = now_s();
|
|
STATE_UNLOCK();
|
|
jlog("usage", "endpoint=%s rc=%d percent=%.1f used_usd=%.2f budget_usd=%.2f ok=%d",
|
|
ep->name, rc, ep->usage_percent, ep->usage_used_usd, ep->usage_budget_usd,
|
|
ep->usage_ok);
|
|
}
|
|
sleep(1);
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
static int ep_in_offpeak(const j_endpoint *ep)
|
|
{
|
|
if (ep->offpeak_from < 0 || ep->offpeak_to < 0) return 0;
|
|
time_t t = time(NULL);
|
|
struct tm tm;
|
|
localtime_r(&t, &tm);
|
|
int now = tm.tm_hour * 60 + tm.tm_min;
|
|
if (ep->offpeak_from <= ep->offpeak_to)
|
|
return now >= ep->offpeak_from && now < ep->offpeak_to;
|
|
return now >= ep->offpeak_from || now < ep->offpeak_to; /* window wraps midnight */
|
|
}
|
|
|
|
/* Wie gut passt dieser Endpunkt gerade? Kleiner ist besser.
|
|
*
|
|
* Das Gewicht wirkt zweifach, und das ist Absicht: im Modus "cost" teilt es den Preis
|
|
* (ein Ziel mit Gewicht 3 gilt als dreimal so teuer, wird also seltener genommen), im
|
|
* Modus "least-usage" verschiebt es den Verbrauch nach oben. Wer ein starkes Ziel
|
|
* bevorzugen will, gibt ihm ein kleines Gewicht — dieselbe Richtung wie "billiger". */
|
|
static double ep_score(const j_endpoint *ep)
|
|
{
|
|
double usage = ep->usage_ok ? ep->usage_percent : 0.0;
|
|
double w = (double)ep->weight;
|
|
if (CFG.balance == J_BALANCE_COST)
|
|
return (ep_in_offpeak(ep) ? 0.0 : 1000.0) + (usage / w) * (ep->cost_weight > 0 ? ep->cost_weight : 1.0);
|
|
return usage / w;
|
|
}
|
|
|
|
/* Order the rule's targets according to the configured balance mode. "first"
|
|
* keeps rule order, which is what a failover chain wants; the others sort. */
|
|
static pthread_mutex_t g_rr_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
static void balance_order(const j_rule *r, int *order, int n)
|
|
{
|
|
static unsigned long rr_turn;
|
|
/* Die Regel darf das Verfahren überschreiben; sonst gilt das globale. */
|
|
int mode = (r->balance >= 0) ? r->balance : CFG.balance;
|
|
|
|
for (int i = 0; i < n; i++) order[i] = i;
|
|
if (mode == J_BALANCE_FIRST || n < 2) return;
|
|
|
|
if (mode == J_BALANCE_RR) {
|
|
/* Gewichtetes Reihum: ein Ziel mit Gewicht 3 bekommt drei Plätze in der Runde.
|
|
* Das ist die einfache, nachvollziehbare Form — kein Glätten über Zeit, sondern
|
|
* eine feste Reihenfolge, in der jedes Ziel so oft vorkommt, wie es wiegt. */
|
|
int slots[J_MAX_TARGETS * 8];
|
|
int ns = 0;
|
|
for (int i = 0; i < n && ns < (int)(sizeof slots / sizeof slots[0]); i++) {
|
|
const j_endpoint *x = NULL;
|
|
for (int k = 0; k < CFG.endpoint_count; k++)
|
|
if (!strcmp(CFG.endpoints[k].name, r->targets[i])) { x = &CFG.endpoints[k]; break; }
|
|
int reps = x ? x->weight : 1;
|
|
for (int c = 0; c < reps && ns < (int)(sizeof slots / sizeof slots[0]); c++)
|
|
slots[ns++] = i;
|
|
}
|
|
if (!ns) return;
|
|
/* Concurrent requests must get different turns; otherwise two requests
|
|
* starting together both pick the same first target and queue there. */
|
|
pthread_mutex_lock(&g_rr_mu);
|
|
unsigned long turn = rr_turn++;
|
|
pthread_mutex_unlock(&g_rr_mu);
|
|
int shift = (int)(turn % (unsigned long)ns);
|
|
int seen = 0;
|
|
for (int s2 = 0; s2 < ns && seen < n; s2++) {
|
|
int t = slots[(s2 + shift) % ns];
|
|
int schon = 0;
|
|
for (int q = 0; q < seen; q++) if (order[q] == t) { schon = 1; break; }
|
|
if (!schon) order[seen++] = t;
|
|
}
|
|
return;
|
|
}
|
|
|
|
/* least-usage / cost: insertion sort on the score, stable for ties */
|
|
for (int i = 1; i < n; i++) {
|
|
int cur = order[i];
|
|
const j_endpoint *a = NULL, *b = NULL;
|
|
for (int k = 0; k < CFG.endpoint_count; k++) {
|
|
if (!strcmp(CFG.endpoints[k].name, r->targets[cur])) a = &CFG.endpoints[k];
|
|
}
|
|
int j = i - 1;
|
|
while (j >= 0) {
|
|
b = NULL;
|
|
for (int k = 0; k < CFG.endpoint_count; k++)
|
|
if (!strcmp(CFG.endpoints[k].name, r->targets[order[j]])) b = &CFG.endpoints[k];
|
|
if (!b || !a || ep_score(b) <= ep_score(a)) break;
|
|
order[j + 1] = order[j];
|
|
j--;
|
|
}
|
|
order[j + 1] = cur;
|
|
}
|
|
}
|
|
|
|
/* --------------------------------------------------------- virtual keys */
|
|
/* The client authenticates with a key we minted; the real upstream key never
|
|
* leaves this process. A vkey may be restricted to a model glob and to a set of
|
|
* endpoint names. */
|
|
static j_vkey *vkey_lookup(const j_hdrs *h, const char *token)
|
|
{
|
|
(void)h;
|
|
if (!token || !token[0]) return NULL;
|
|
for (int i = 0; i < CFG.vkey_count; i++) {
|
|
const char *real = getenv(CFG.vkeys[i].token_env);
|
|
if (real && real[0] && !strcmp(real, token)) return &CFG.vkeys[i];
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
static int vkey_allows_endpoint(const j_vkey *v, const char *ep_name)
|
|
{
|
|
if (!v || !v->endpoints[0]) return 1;
|
|
char list[J_URL_MAX];
|
|
snprintf(list, sizeof list, "%s", v->endpoints);
|
|
for (char *tok = strtok(list, ","); tok; tok = strtok(NULL, ",")) {
|
|
while (*tok == ' ') tok++;
|
|
if (!strcmp(tok, ep_name)) return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* 429 mit Retry-After: ein Client, der zu schnell war, soll erfahren, wann er wieder
|
|
* darf — sonst wiederholt er im gleichen Takt und die Sperre verlängert sich selbst. */
|
|
static void send_limited(j_conn *c, int code, const char *reason, double retry_after,
|
|
const char *vkey)
|
|
{
|
|
char body[320], ev[J_NAME_MAX];
|
|
json_escape(vkey ? vkey : "", ev, sizeof ev);
|
|
snprintf(body, sizeof body, "{\"error\":\"%s\",\"vkey\":\"%s\"}", reason, ev);
|
|
char hdr[512];
|
|
int secs = retry_after > 0 ? (int)(retry_after + 0.999) : 0;
|
|
int n = snprintf(hdr, sizeof hdr,
|
|
"HTTP/1.1 %d %s\r\nContent-Type: application/json\r\n"
|
|
"Retry-After: %d\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n",
|
|
code, (code == 429) ? "Too Many Requests" : "Forbidden",
|
|
secs, strlen(body));
|
|
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);
|
|
}
|
|
|
|
/* Wächter: gibt den Rumpf an ein Skript und lässt es entscheiden. Der Rumpf liegt in
|
|
* einer temporären Datei statt auf stdin — ein Skript, das nur einen Teil liest, würde
|
|
* sonst beim Schreiben in eine volle Pipe hängen. Exit 0 = durchlassen; alles andere
|
|
* ist eine Ablehnung, und was das Skript auf stdout sagt, ist der Grund. */
|
|
static int guard_run(const char *cmd, const char *body, size_t len, const char *path,
|
|
const char *model, const char *vkey, char *reason, size_t rlen)
|
|
{
|
|
char tmp[] = "/tmp/junction-guard-XXXXXX";
|
|
int fd = mkstemp(tmp);
|
|
if (fd < 0) {
|
|
snprintf(reason, rlen, "guard_tempfile_failed");
|
|
return -1;
|
|
}
|
|
size_t off = 0;
|
|
while (off < len) {
|
|
ssize_t w = write(fd, body + off, len - off);
|
|
if (w <= 0) break;
|
|
off += (size_t)w;
|
|
}
|
|
close(fd);
|
|
|
|
int out[2];
|
|
if (pipe(out) != 0) {
|
|
unlink(tmp);
|
|
snprintf(reason, rlen, "guard_pipe_failed");
|
|
return -1;
|
|
}
|
|
pid_t pid = fork();
|
|
if (pid < 0) {
|
|
close(out[0]);
|
|
close(out[1]);
|
|
unlink(tmp);
|
|
snprintf(reason, rlen, "guard_fork_failed");
|
|
return -1;
|
|
}
|
|
if (pid == 0) {
|
|
dup2(out[1], STDOUT_FILENO);
|
|
dup2(out[1], STDERR_FILENO);
|
|
close(out[0]);
|
|
close(out[1]);
|
|
char nbuf[32];
|
|
setenv("JUNCTION_PATH", path ? path : "", 1);
|
|
setenv("JUNCTION_MODEL", model ? model : "", 1);
|
|
setenv("JUNCTION_VKEY", vkey ? vkey : "", 1);
|
|
setenv("JUNCTION_BODY_FILE", tmp, 1);
|
|
snprintf(nbuf, sizeof nbuf, "%zu", len);
|
|
setenv("JUNCTION_BODY_BYTES", nbuf, 1);
|
|
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
|
|
_exit(127);
|
|
}
|
|
close(out[1]);
|
|
|
|
if (rlen) reason[0] = '\0';
|
|
size_t used = 0;
|
|
double deadline = now_s() + 20.0;
|
|
int status = 0;
|
|
for (;;) {
|
|
if (now_s() >= deadline) { kill(pid, SIGKILL); break; }
|
|
struct pollfd p = { .fd = out[0], .events = POLLIN, .revents = 0 };
|
|
if (poll(&p, 1, 100) > 0 && (p.revents & POLLIN)) {
|
|
char tmpb[256];
|
|
ssize_t n = read(out[0], tmpb, sizeof tmpb);
|
|
if (n > 0 && rlen && used < rlen - 1) {
|
|
size_t take = (size_t)n;
|
|
if (take > rlen - 1 - used) take = rlen - 1 - used;
|
|
memcpy(reason + used, tmpb, take);
|
|
used += take;
|
|
reason[used] = '\0';
|
|
}
|
|
}
|
|
if (waitpid(pid, &status, WNOHANG) == pid) break;
|
|
}
|
|
close(out[0]);
|
|
unlink(tmp);
|
|
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
|
|
/* Leere Begründung ist keine: dann nennt junction den Exit-Code. */
|
|
if (rlen && !reason[0])
|
|
snprintf(reason, rlen, "guard_exit_%d", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
|
return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int wait_until_ready(j_endpoint *ep, const char *path, const char *model,
|
|
long need, double retry_s, int use_hooks)
|
|
{
|
|
double deadline = now_s() + (retry_s > 0 ? retry_s : 0);
|
|
int attempt = 1, woke = 0;
|
|
for (;;) {
|
|
int failing = 0;
|
|
if (use_hooks) {
|
|
for (int i = 0; i < ep->hook_count; i++) {
|
|
char reason[256];
|
|
if (run_cmd(ep->hooks[i], ep, path, model, need, attempt, reason, sizeof reason)) {
|
|
STATE_LOCK();
|
|
snprintf(ep->last_hook_reason, sizeof ep->last_hook_reason, "%s", reason);
|
|
STATE_UNLOCK();
|
|
failing = 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!failing) return 0;
|
|
if (now_s() >= deadline) return -1;
|
|
if (ep->wake[0] && !woke) {
|
|
jlog("wake_start", "endpoint=%s cmd=%s", ep->name, ep->wake);
|
|
char r[128];
|
|
woke = (run_cmd(ep->wake, ep, path, model, need, attempt, r, sizeof r) == 0);
|
|
}
|
|
jlog("waiting", "endpoint=%s reason=%s attempt=%d budget_left=%.1f",
|
|
ep->name, ep->last_hook_reason, attempt, deadline - now_s());
|
|
double b = ep->hook_backoff_s > 0 ? ep->hook_backoff_s : 1.0;
|
|
struct timespec ts = { (time_t)b, (time_t)((b - (time_t)b) * 1e9) };
|
|
nanosleep(&ts, NULL);
|
|
attempt++;
|
|
}
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ relaying */
|
|
/* Copy what the upstream sends, preserving its framing (chunked stays chunked).
|
|
* Used for streamed responses, which must not be buffered. */
|
|
static int relay_stream(j_conn *client, j_conn *up, const char *pre, size_t pre_len,
|
|
long content_length, double idle_s, double deadline)
|
|
{
|
|
char err[192];
|
|
static char buf[RELAY_CHUNK];
|
|
long remaining = content_length;
|
|
if (pre && pre_len) {
|
|
if (j_conn_write(client, pre, pre_len, err, sizeof err) < 0) return -2;
|
|
/* these bytes are part of the body too — forgetting this made every
|
|
* Content-Length response end in a bogus relay failure */
|
|
if (remaining > 0) remaining -= (long)pre_len;
|
|
}
|
|
for (;;) {
|
|
if (remaining == 0) return 0;
|
|
if (wait_readable(up, idle_s, deadline) != 1) return -1;
|
|
size_t want = sizeof buf;
|
|
if (remaining > 0 && (long)want > remaining) want = (size_t)remaining;
|
|
ssize_t n = j_conn_read(up, buf, want, err, sizeof err);
|
|
if (n < 0) return -1;
|
|
if (n == 0) return remaining > 0 ? -1 : 0;
|
|
if (j_conn_write(client, buf, (size_t)n, err, sizeof err) < 0) return -2;
|
|
if (remaining > 0) remaining -= n;
|
|
}
|
|
}
|
|
|
|
/* Relay a chunked upstream body to the client WITHOUT the chunk framing.
|
|
*
|
|
* Why this exists: the client's response head is written before the upstream is even
|
|
* chosen on a streaming request, so Transfer-Encoding cannot be added afterwards. The
|
|
* old code forwarded the raw framing, and the client read the hex size lines as
|
|
* content — Hermes saw `f\r\ndata: …` and reported a truncated JSON body while
|
|
* junction logged relay_failed. De-chunking here keeps the bytes identical to what
|
|
* the upstream meant to send; the body ends when the connection closes. */
|
|
static int relay_dechunk(j_conn *client, j_conn *up, const char *pre, size_t pre_len,
|
|
double idle_s, double deadline)
|
|
{
|
|
char err[192];
|
|
static char in[RELAY_CHUNK * 2];
|
|
size_t have = 0;
|
|
if (pre && pre_len) {
|
|
if (pre_len > sizeof in) return -1;
|
|
memcpy(in, pre, pre_len);
|
|
have = pre_len;
|
|
}
|
|
long chunk_left = -1; /* bytes still to copy of the current chunk, -1 = need size */
|
|
int at_line = 1; /* expecting a chunk-size line */
|
|
for (;;) {
|
|
if (at_line) {
|
|
/* look for CRLF in the buffer */
|
|
size_t i = 0;
|
|
while (i + 1 < have && !(in[i] == '\r' && in[i + 1] == '\n')) i++;
|
|
if (i + 1 >= have) {
|
|
if (have == sizeof in) return -1; /* size line never ends */
|
|
if (wait_readable(up, idle_s, deadline) != 1) return -1;
|
|
ssize_t n = j_conn_read(up, in + have, sizeof in - have, err, sizeof err);
|
|
if (n <= 0) return -1;
|
|
have += (size_t)n;
|
|
continue;
|
|
}
|
|
char num[32];
|
|
size_t nl = i < sizeof num - 1 ? i : sizeof num - 1;
|
|
memcpy(num, in, nl);
|
|
num[nl] = '\0';
|
|
long sz = strtol(num, NULL, 16);
|
|
/* drop the line (plus an optional chunk extension) */
|
|
size_t consumed = i + 2;
|
|
memmove(in, in + consumed, have - consumed);
|
|
have -= consumed;
|
|
if (sz <= 0) {
|
|
/* last chunk: swallow the trailer and stop */
|
|
return 0;
|
|
}
|
|
chunk_left = sz;
|
|
at_line = 0;
|
|
}
|
|
if (chunk_left > 0) {
|
|
if (have == 0) {
|
|
if (wait_readable(up, idle_s, deadline) != 1) return -1;
|
|
ssize_t n = j_conn_read(up, in, sizeof in, err, sizeof err);
|
|
if (n <= 0) return -1;
|
|
have = (size_t)n;
|
|
}
|
|
size_t copy = have < (size_t)chunk_left ? have : (size_t)chunk_left;
|
|
if (j_conn_write(client, in, copy, err, sizeof err) < 0) return -2;
|
|
memmove(in, in + copy, have - copy);
|
|
have -= copy;
|
|
chunk_left -= (long)copy;
|
|
continue;
|
|
}
|
|
/* end of chunk data: expect CRLF, then the next size line */
|
|
if (have < 2) {
|
|
if (wait_readable(up, idle_s, deadline) != 1) return -1;
|
|
ssize_t n = j_conn_read(up, in + have, sizeof in - have, err, sizeof err);
|
|
if (n <= 0) return -1;
|
|
have += (size_t)n;
|
|
continue;
|
|
}
|
|
if (in[0] == '\r' && in[1] == '\n') {
|
|
memmove(in, in + 2, have - 2);
|
|
have -= 2;
|
|
}
|
|
at_line = 1;
|
|
}
|
|
}
|
|
|
|
/* Read a complete body (chunked or Content-Length) into memory. */
|
|
static int read_full_body(j_conn *up, j_buf *buf, size_t off, int chunked, long content_length,
|
|
double idle_s, double deadline, char **body, size_t *body_len,
|
|
char *err, size_t errlen)
|
|
{
|
|
if (chunked)
|
|
return j_chunked_read(up, buf, off, (size_t)CFG.max_body_bytes, idle_s, deadline,
|
|
body, body_len, err, errlen);
|
|
if (content_length <= 0) {
|
|
*body = calloc(1, 1);
|
|
*body_len = 0;
|
|
return *body ? 0 : -1;
|
|
}
|
|
if (content_length > CFG.max_body_bytes) { snprintf(err, errlen, "response_too_large"); return -1; }
|
|
if (j_buf_ensure(up, buf, off, (size_t)content_length, idle_s, deadline, err, errlen)) return -1;
|
|
char *b = malloc((size_t)content_length + 1);
|
|
if (!b) { snprintf(err, errlen, "oom"); return -1; }
|
|
memcpy(b, buf->data + off, (size_t)content_length);
|
|
b[content_length] = '\0';
|
|
*body = b;
|
|
*body_len = (size_t)content_length;
|
|
return 0;
|
|
}
|
|
|
|
/* Send a status line + headers; body_len >= 0 sets Content-Length. */
|
|
static int send_head(j_conn *client, int status, const char *reason, j_hdrs *h,
|
|
long body_len, char *err, size_t errlen)
|
|
{
|
|
if (body_len >= 0) {
|
|
char cl[J_HDR_VALUE];
|
|
snprintf(cl, sizeof cl, "%ld", body_len);
|
|
j_hdrs_set(h, "Content-Length", cl);
|
|
j_hdrs_del(h, "Transfer-Encoding");
|
|
} else if (body_len == -1) {
|
|
/* Chunked relay: the BODY keeps the upstream's chunk framing, so the client
|
|
* must be told that — otherwise it reads the hex size lines as content. The
|
|
* hop-by-hop filter drops Transfer-Encoding by definition, so it is set here
|
|
* and serialized without that filter; the other hop headers are removed. */
|
|
j_hdrs_del(h, "Keep-Alive");
|
|
j_hdrs_del(h, "Proxy-Authenticate");
|
|
j_hdrs_del(h, "Proxy-Authorization");
|
|
j_hdrs_del(h, "TE");
|
|
j_hdrs_del(h, "Trailer");
|
|
j_hdrs_del(h, "Upgrade");
|
|
j_hdrs_set(h, "Transfer-Encoding", "chunked");
|
|
} else {
|
|
/* -2: the de-chunked body is forwarded as-is and ends when the connection
|
|
* closes, so neither Content-Length nor Transfer-Encoding is announced. */
|
|
j_hdrs_del(h, "Transfer-Encoding");
|
|
j_hdrs_del(h, "Content-Length");
|
|
j_hdrs_del(h, "Keep-Alive");
|
|
}
|
|
j_hdrs_set(h, "Connection", "close");
|
|
|
|
char *out = malloc(HDR_BLOCK_MAX);
|
|
if (!out) { snprintf(err, errlen, "oom"); return -1; }
|
|
size_t used = (size_t)snprintf(out, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", status,
|
|
reason[0] ? reason : "OK");
|
|
used += j_hdrs_serialize(h, out + used, HDR_BLOCK_MAX - used, body_len >= 0 ? 1 : 0, 1);
|
|
int rc = j_conn_write(client, out, used, err, errlen) < 0 ? -1 : 0;
|
|
free(out);
|
|
return rc;
|
|
}
|
|
|
|
/* --------------------------------------------------------------- forwarding */
|
|
typedef struct {
|
|
int status;
|
|
char reason[64];
|
|
j_hdrs hdrs;
|
|
j_buf buf;
|
|
size_t body_off;
|
|
int chunked;
|
|
long content_length;
|
|
} j_upstream_resp;
|
|
|
|
static void resp_free(j_upstream_resp *r)
|
|
{
|
|
j_buf_free(&r->buf);
|
|
}
|
|
|
|
static int read_response(j_conn *up, j_upstream_resp *r, double idle_s, double deadline,
|
|
char *err, size_t errlen)
|
|
{
|
|
memset(r, 0, sizeof *r);
|
|
j_hdrs_init(&r->hdrs);
|
|
j_buf_init(&r->buf);
|
|
ssize_t head_len = j_buf_read_until(up, &r->buf, "\r\n\r\n", HDR_BLOCK_MAX, idle_s,
|
|
deadline, err, errlen);
|
|
if (head_len <= 0) {
|
|
if (head_len == -2) snprintf(err, errlen, "no_response_headers");
|
|
return -1;
|
|
}
|
|
r->body_off = (size_t)head_len;
|
|
|
|
char *line_end = strstr(r->buf.data, "\r\n");
|
|
if (!line_end) { snprintf(err, errlen, "unparsable_status_line"); return -1; }
|
|
size_t line_len = (size_t)(line_end - r->buf.data);
|
|
char line[512];
|
|
if (line_len >= sizeof line) { snprintf(err, errlen, "status_line_too_long"); return -1; }
|
|
memcpy(line, r->buf.data, line_len);
|
|
line[line_len] = '\0';
|
|
if (sscanf(line, "HTTP/%*d.%*d %d %63[^\r\n]", &r->status, r->reason) < 1) {
|
|
snprintf(err, errlen, "unparsable_status_line");
|
|
return -1;
|
|
}
|
|
const char *hdr_start = line_end + 2;
|
|
size_t hdr_len = (size_t)((r->buf.data + head_len - 4) - hdr_start);
|
|
j_hdrs_parse(&r->hdrs, hdr_start, hdr_len);
|
|
|
|
char te[J_HDR_VALUE], cl[J_HDR_VALUE];
|
|
r->chunked = !j_hdrs_find(&r->hdrs, "Transfer-Encoding", te, sizeof te) &&
|
|
strstr(te, "chunked") != NULL;
|
|
r->content_length = -1;
|
|
if (!j_hdrs_find(&r->hdrs, "Content-Length", cl, sizeof cl))
|
|
r->content_length = strtol(cl, NULL, 10);
|
|
return 0;
|
|
}
|
|
|
|
/* Ein 429/5xx nennt im Rumpf fast immer den Grund ("monthly usage limit",
|
|
* "context exhausted", ...). Ohne ihn bleibt im Log nur der Status, und die Ursache
|
|
* muss von Hand nachgestellt werden. Best effort: kurze Frist, gekappte Länge,
|
|
* Steuerzeichen werden zu Leerzeichen. */
|
|
static void log_upstream_error_body(j_conn *up, j_upstream_resp *r, const char *endpoint)
|
|
{
|
|
char body_err[96];
|
|
char *body = NULL;
|
|
size_t len = 0;
|
|
|
|
if (read_full_body(up, &r->buf, r->body_off, r->chunked, r->content_length,
|
|
0.5, now_s() + 1.0, &body, &len, body_err, sizeof body_err) != 0)
|
|
return;
|
|
if (body != NULL && len > 0) {
|
|
char snip[241];
|
|
size_t n = len > 200 ? 200 : len, o = 0, spaces = 0;
|
|
for (size_t i = 0; i < n; i++) {
|
|
unsigned char c = (unsigned char)body[i];
|
|
if (c >= 32 && c < 127) {
|
|
snip[o++] = (char)c;
|
|
spaces = c == ' ' ? spaces + 1 : 0;
|
|
if (spaces > 1) o--; /* collapse runs, keep the line short */
|
|
} else if (o > 0 && snip[o - 1] != ' ') {
|
|
snip[o++] = ' ';
|
|
spaces = 1;
|
|
}
|
|
}
|
|
while (o > 0 && snip[o - 1] == ' ') o--;
|
|
snip[o] = '\0';
|
|
jlog("upstream_error", "endpoint=%s status=%d body=%s", endpoint, r->status, snip);
|
|
}
|
|
free(body);
|
|
}
|
|
|
|
/* Returns 0 = served, -1 = endpoint failed (fail over), -2 = bytes already sent to the
|
|
* client, so failing over is impossible. */
|
|
static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
|
|
const char *out_body, size_t out_len, const char *as_model,
|
|
const char *rq_model, const char *cache_state, double req_started,
|
|
int head_sent, const char *vkey_name, char *err, size_t errlen)
|
|
{
|
|
char host[J_NAME_MAX], port[16], prefix[J_URL_MAX];
|
|
int tls = 0;
|
|
if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix, &tls)) {
|
|
snprintf(err, errlen, "bad_base_url");
|
|
return -1;
|
|
}
|
|
|
|
/* The model this endpoint answers to may differ from what was asked for.
|
|
* The rewrite runs first, so the effort selector from the rule's target or
|
|
* from the client's model#effort is in the body when the dialect normalizer
|
|
* sees it. cache_body stays the pre-normalized request: the cache lookup in
|
|
* handle_client used that body, and a fill under a different key would never
|
|
* be found again. */
|
|
char *body_alloc = NULL;
|
|
const char *cache_body = out_body;
|
|
size_t cache_len = out_len;
|
|
|
|
if (as_model && as_model[0] && out_body) {
|
|
char target_model[256];
|
|
model_for_target(as_model, rq_model, target_model, sizeof target_model);
|
|
char *rewritten = rewrite_model(out_body, target_model);
|
|
if (rewritten) {
|
|
body_alloc = rewritten;
|
|
out_body = rewritten;
|
|
out_len = strlen(rewritten);
|
|
cache_body = rewritten;
|
|
cache_len = out_len;
|
|
}
|
|
}
|
|
|
|
/* OpenAI-compatible endpoints take reasoning_effort; Anthropic takes
|
|
* output_config.effort. opencode's bridge reads the selector from the model
|
|
* itself and must not have it stripped here. */
|
|
if (out_body && strcmp(ep->kind, "opencode") != 0) {
|
|
char *normalized = NULL;
|
|
size_t normalized_len = 0;
|
|
int changed;
|
|
if (!strcmp(ep->kind, "anthropic") &&
|
|
(!strncmp(rq->path, "/v1/messages", 12) &&
|
|
(rq->path[12] == '\0' || rq->path[12] == '?')))
|
|
changed = j_effort_anthropic(out_body, out_len, &normalized, &normalized_len);
|
|
else if (strcmp(ep->kind, "anthropic") != 0)
|
|
changed = j_effort_openai(out_body, out_len, &normalized, &normalized_len);
|
|
else
|
|
changed = -1;
|
|
if (changed == 0) {
|
|
free(body_alloc);
|
|
body_alloc = normalized;
|
|
out_body = normalized;
|
|
out_len = normalized_len;
|
|
}
|
|
}
|
|
|
|
j_conn up = J_CONN_INIT;
|
|
if (j_conn_open(&up, host, port, tls, tls ? ep->tls_verify : 0, ep->tls_ca,
|
|
ep->connect_timeout_ms > 0 ? ep->connect_timeout_ms : CFG.connect_timeout_ms,
|
|
err, errlen)) {
|
|
free(body_alloc);
|
|
return -1;
|
|
}
|
|
up.role = "upstream";
|
|
|
|
char target[4096];
|
|
if (!strncmp(rq->path, "/v1", 3))
|
|
snprintf(target, sizeof target, "%s%s", prefix, rq->path + 3);
|
|
else
|
|
snprintf(target, sizeof target, "%s%s", prefix, rq->path);
|
|
|
|
char *req = malloc(HDR_BLOCK_MAX);
|
|
if (!req) { snprintf(err, errlen, "oom"); j_conn_close(&up); free(body_alloc); return -1; }
|
|
size_t used = (size_t)snprintf(req, HDR_BLOCK_MAX, "%s %s HTTP/1.1\r\n", rq->method, target);
|
|
|
|
/* Forward the client's headers, but not the ones we own. Forwarding the client's
|
|
* Host gave the upstream TWO Host headers, and its Content-Length plus ours gave
|
|
* it two lengths — Ollama answered 400 for a request that was valid.
|
|
*
|
|
* Authorization is the same class of bug: when this endpoint injects its own key,
|
|
* 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 = 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);
|
|
int anthropic_kind = !strcmp(ep->kind, "anthropic");
|
|
/* /v1/models is rewritten (policy filter + virtual alias models), so the body
|
|
* must arrive as readable JSON. A provider that gzips the list would slip past
|
|
* the whitelist. Ask for identity here; every other path keeps the client's
|
|
* Accept-Encoding. */
|
|
int models_path = !strncmp(rq->path, "/v1/models", 10);
|
|
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;
|
|
if (!strcasecmp(name, "Host") || !strcasecmp(name, "Content-Length") ||
|
|
(inject_auth && !strcasecmp(name, "Authorization")) ||
|
|
(inject_auth && anthropic_kind && !strcasecmp(name, "x-api-key")) ||
|
|
(models_path && !strcasecmp(name, "Accept-Encoding")) ||
|
|
!strcasecmp(name, "Transfer-Encoding") ||
|
|
!strcasecmp(name, "X-Forwarded-For") || !strcasecmp(name, "X-Forwarded-Proto") ||
|
|
!strncasecmp(name, "X-Junction-", 11))
|
|
continue;
|
|
int n = snprintf(req + used, HDR_BLOCK_MAX - used, "%s: %s\r\n", name,
|
|
rq->hdrs.it[i].value);
|
|
if (n < 0) break;
|
|
used += (size_t)n;
|
|
if (used >= HDR_BLOCK_MAX - 256) break;
|
|
}
|
|
|
|
char hosthdr[300];
|
|
if ((!tls && !strcmp(port, "80")) || (tls && !strcmp(port, "443")))
|
|
snprintf(hosthdr, sizeof hosthdr, "%s", host);
|
|
else
|
|
snprintf(hosthdr, sizeof hosthdr, "%s:%s", host, port);
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Host: %s\r\n", hosthdr);
|
|
|
|
if (inject_auth)
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
|
"Authorization: Bearer %s\r\n", inj_key);
|
|
char av[J_HDR_VALUE];
|
|
int have_av = anthropic_kind &&
|
|
j_hdrs_find(&rq->hdrs, "anthropic-version", av, sizeof av) == 0 &&
|
|
av[0] != '\0';
|
|
for (int i = 0; i < ep->header_count; i++) {
|
|
if (strchr(ep->headers[i], '\r') || strchr(ep->headers[i], '\n')) continue;
|
|
if (models_path && !strncasecmp(ep->headers[i], "Accept-Encoding:", 16)) continue;
|
|
if (have_av && !strncasecmp(ep->headers[i], "anthropic-version:", 18)) continue;
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "%s\r\n", ep->headers[i]);
|
|
}
|
|
if (models_path)
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
|
"Accept-Encoding: identity\r\n");
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
|
"X-Forwarded-Proto: %s\r\nX-Junction-Endpoint: %s\r\n",
|
|
tls ? "https" : "http", ep->name);
|
|
char xff[J_HDR_VALUE];
|
|
int have_xff = (j_hdrs_find(&rq->hdrs, "X-Forwarded-For", xff, sizeof xff) == 0 &&
|
|
xff[0] != '\0');
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "X-Forwarded-For: %s%s127.0.0.1\r\n",
|
|
have_xff ? xff : "", have_xff ? ", " : "");
|
|
if (out_body && out_len)
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used,
|
|
"Content-Length: %zu\r\n", out_len);
|
|
used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Connection: close\r\n\r\n");
|
|
|
|
if (used >= HDR_BLOCK_MAX - 2) {
|
|
snprintf(err, errlen, "request_headers_too_large");
|
|
free(req);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -1;
|
|
}
|
|
|
|
/* J_DUMP_REQ=<file>: write exactly what goes upstream, with the credentials
|
|
* masked. Exists because a strict frontend (Cloudflare) rejects what a lenient
|
|
* one (Ollama) accepts, and guessing from the outside wastes hours. */
|
|
const char *dump_path = getenv("J_DUMP_REQ");
|
|
if (dump_path && dump_path[0]) {
|
|
FILE *df = fopen(dump_path, "a");
|
|
if (df) {
|
|
fprintf(df, "--- %s %s -> %s (%s) ---\n", rq->method, target, ep->name,
|
|
tls ? "tls" : "plain");
|
|
const char *p = req;
|
|
while (*p) {
|
|
const char *nl = strchr(p, '\n');
|
|
size_t len = nl ? (size_t)(nl - p + 1) : strlen(p);
|
|
if (!strncasecmp(p, "Authorization:", 14))
|
|
fprintf(df, "Authorization: <masked>\n");
|
|
else
|
|
fwrite(p, 1, len, df);
|
|
if (!nl) break;
|
|
p = nl + 1;
|
|
}
|
|
if (out_body && out_len) {
|
|
fputs("=== BODY ===\n", df);
|
|
fwrite(out_body, 1, out_len, df);
|
|
fputc('\n', df);
|
|
}
|
|
fclose(df);
|
|
}
|
|
}
|
|
|
|
if (j_conn_write(&up, req, used, err, errlen) < 0 ||
|
|
(out_body && out_len && j_conn_write(&up, out_body, out_len, err, errlen) < 0)) {
|
|
free(req);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -1;
|
|
}
|
|
free(req);
|
|
|
|
double deadline = now_s() + ep->timeout_s;
|
|
up.heartbeat_s = head_sent ? 10 : 0; /* wake the reader every 10 s for a stream */
|
|
if (head_sent) {
|
|
t_heartbeat = client;
|
|
t_heartbeat_started = now_s();
|
|
}
|
|
j_upstream_resp r;
|
|
int rr = read_response(&up, &r, ep->idle_timeout_s, deadline, err, errlen);
|
|
if (rr) {
|
|
t_heartbeat = NULL;
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -1;
|
|
}
|
|
if (r.status >= 500 || r.status == 429) {
|
|
t_heartbeat = NULL;
|
|
log_upstream_error_body(&up, &r, ep->name);
|
|
snprintf(err, errlen, "upstream_status_%d", r.status);
|
|
/* Was der Anbieter selbst sagt, ist besser als jede eigene Wartezeit: bei 429
|
|
* und 503 steht dort oft, wann es wieder geht. Nur Sekunden werden gelesen —
|
|
* ein HTTP-Datum wäre eine Zeitzonen-Frage, und ohne Antwort ist 0 richtig. */
|
|
{
|
|
char ra[J_HDR_VALUE];
|
|
t_retry_after_s = 0;
|
|
if (!j_hdrs_find(&r.hdrs, "Retry-After", ra, sizeof ra))
|
|
t_retry_after_s = retry_after_seconds(ra);
|
|
}
|
|
STATE_LOCK();
|
|
snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", r.status);
|
|
STATE_UNLOCK();
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -1;
|
|
}
|
|
/* Once the stream head is out the caller has a 200; anything that goes wrong from
|
|
* here has to be an event, and failing over is no longer possible. */
|
|
if (head_sent && r.status >= 400) {
|
|
char msg[256];
|
|
snprintf(msg, sizeof msg, "%s answered %d %s", ep->name, r.status, r.reason);
|
|
char *body = NULL;
|
|
size_t body_len = 0;
|
|
if (read_full_body(&up, &r.buf, r.body_off, r.chunked, r.content_length,
|
|
ep->idle_timeout_s, deadline, &body, &body_len, err, errlen) == 0) {
|
|
if (body_len) {
|
|
char *m = malloc(body_len + 128);
|
|
if (m) {
|
|
snprintf(m, body_len + 128, "%s: %.*s", msg, (int)(body_len > 400 ? 400 : body_len), body);
|
|
sse_error(client, r.status, m);
|
|
free(m);
|
|
} else {
|
|
sse_error(client, r.status, msg);
|
|
}
|
|
} else {
|
|
sse_error(client, r.status, msg);
|
|
}
|
|
free(body);
|
|
} else {
|
|
sse_error(client, r.status, msg);
|
|
}
|
|
t_heartbeat = NULL;
|
|
if (!err[0]) snprintf(err, errlen, "client_stream_failed");
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -2;
|
|
}
|
|
|
|
char cc[J_HDR_VALUE];
|
|
int resp_no_store = !j_hdrs_find(&r.hdrs, "Cache-Control", cc, sizeof cc) &&
|
|
(strstr(cc, "no-store") || strstr(cc, "private"));
|
|
int store = (CFG.cache_ttl_s > 0) && (ep->cache_on != 0) && (r.status == 200) &&
|
|
!resp_no_store && out_len > 0 && !json_bool_value(out_body, "stream");
|
|
|
|
/* Verbrauch lässt sich nur zählen, wenn die Antwort ganz vorliegt. Bei gesetzter
|
|
* Preistabelle wird deshalb auch ohne Cache vollständig gelesen — ein nicht
|
|
* gestreamter JSON-Rumpf ist ohnehin endlich. */
|
|
int want_usage = (j_price_count() > 0) && !r.chunked && (r.status == 200);
|
|
/* Auch eine chunked Modellliste wird gelesen und gefiltert: eine Politik, die
|
|
* ein Anbieter mit Transfer-Encoding umgehen kann, ist keine Politik. */
|
|
int want_models_rewrite = (r.status == 200 &&
|
|
!strncmp(rq->path, "/v1/models", 10));
|
|
|
|
char msbuf[32];
|
|
snprintf(msbuf, sizeof msbuf, "%ld", (long)((now_s() - req_started) * 1000.0));
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Endpoint", ep->name);
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf);
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Cache", cache_state);
|
|
|
|
/* Verbrauch und Kosten über den Block hinaus, damit die Logzeile auch dann
|
|
* geschrieben wird, wenn die Antwort keine Nutzungszahlen trägt: eine Anfrage, die
|
|
* beantwortet wurde, gehört ins Log — mit Nullen, nicht gar nicht. */
|
|
long l_in = 0, l_out = 0, l_cached = 0;
|
|
double l_cost = -1.0;
|
|
|
|
if ((store || want_usage || want_models_rewrite) && !head_sent) {
|
|
char *body = NULL;
|
|
size_t body_len = 0;
|
|
if (read_full_body(&up, &r.buf, r.body_off, r.chunked, r.content_length,
|
|
ep->idle_timeout_s, deadline, &body, &body_len, err, errlen)) {
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -1; /* nothing sent yet, failover is safe */
|
|
}
|
|
/* Verbrauch zählen, bevor die Antwort rausgeht: die Zahlen stehen dann in den
|
|
* Kopfzeilen und im /status, nicht nur im Log. */
|
|
{
|
|
long u_in = 0, u_out = 0, u_cached = 0;
|
|
if (!r.chunked && usage_from_body(body, body_len, &u_in, &u_out, &u_cached)) {
|
|
l_in = u_in;
|
|
l_out = u_out;
|
|
l_cached = u_cached;
|
|
const char *billed = (as_model && as_model[0]) ? as_model : rq_model;
|
|
double cost = j_price_cost(billed, u_in, u_cached, u_out, ep->offpeak_active);
|
|
STATE_LOCK();
|
|
ep->tokens_in += (unsigned long)u_in;
|
|
ep->tokens_out += (unsigned long)u_out;
|
|
ep->tokens_cached += (unsigned long)u_cached;
|
|
if (cost >= 0) ep->cost_usd += cost;
|
|
else ep->cost_unknown++;
|
|
STATE_UNLOCK();
|
|
g_tokens_in += (unsigned long)u_in;
|
|
g_tokens_out += (unsigned long)u_out;
|
|
g_tokens_cached += (unsigned long)u_cached;
|
|
if (cost >= 0) g_cost_usd += cost;
|
|
else g_cost_unknown++;
|
|
/* Wem gehört diese Anfrage? Das Spend-Log ist die Buchführung, das
|
|
* Budget des vkey liest daraus — ohne diese Zeile wäre beides nur
|
|
* ein Zähler, der beim Neustart verschwindet. */
|
|
if (vkey_name && vkey_name[0] && cost >= 0) {
|
|
STATE_LOCK();
|
|
for (int i = 0; i < CFG.vkey_count; i++)
|
|
if (!strcmp(CFG.vkeys[i].name, vkey_name)) {
|
|
CFG.vkeys[i].spent_usd += cost;
|
|
break;
|
|
}
|
|
STATE_UNLOCK();
|
|
}
|
|
l_cost = cost;
|
|
|
|
char v[64];
|
|
snprintf(v, sizeof v, "%ld", u_in);
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Tokens-In", v);
|
|
snprintf(v, sizeof v, "%ld", u_out);
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Tokens-Out", v);
|
|
if (cost >= 0) {
|
|
snprintf(v, sizeof v, "%.6f", cost);
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Cost-Usd", v);
|
|
jlog("usage", "model=%s in=%ld cached=%ld out=%ld cost_usd=%.6f",
|
|
billed, u_in, u_cached, u_out, cost);
|
|
} else {
|
|
j_hdrs_set(&r.hdrs, "X-Junction-Cost-Usd", "unknown");
|
|
jlog("usage", "model=%s in=%ld cached=%ld out=%ld cost_usd=unknown",
|
|
billed, u_in, u_cached, u_out);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* /v1/models: erst die Modell-Politik anwenden, dann virtuelle
|
|
* Fallback-/Pool-Alias-Modelle mit effektiver (kleinster) Kontextgröße
|
|
* über die Kette ergänzen/anpassen. */
|
|
if (want_models_rewrite && body && body_len > 0) {
|
|
int changed = 0;
|
|
char *filtered = NULL;
|
|
size_t filtered_len = 0;
|
|
if (j_models_filter_list(body, body_len, &filtered, &filtered_len) == 0 && filtered) {
|
|
free(body);
|
|
body = filtered;
|
|
body_len = filtered_len;
|
|
changed = 1;
|
|
}
|
|
char *patched = NULL;
|
|
size_t patched_len = 0;
|
|
if (j_models_patch_list(body, body_len, &patched, &patched_len) == 0 && patched) {
|
|
free(body);
|
|
body = patched;
|
|
body_len = patched_len;
|
|
changed = 1;
|
|
}
|
|
if (changed) {
|
|
char clv[32];
|
|
snprintf(clv, sizeof clv, "%zu", body_len);
|
|
j_hdrs_set(&r.hdrs, "Content-Length", clv);
|
|
}
|
|
}
|
|
|
|
/* cache the serialized head *with* its final headers, then send the same bytes */
|
|
char *headcopy = malloc(HDR_BLOCK_MAX);
|
|
size_t headused = 0;
|
|
if (headcopy) {
|
|
headused = (size_t)snprintf(headcopy, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n",
|
|
r.status, r.reason[0] ? r.reason : "OK");
|
|
j_hdrs tmp = r.hdrs;
|
|
headused += j_hdrs_serialize(&tmp, headcopy + headused, HDR_BLOCK_MAX - headused,
|
|
1, 1);
|
|
uint64_t fill_key = j_cache_key(rq->method, rq->path, rq_model, cache_body, cache_len);
|
|
j_cache_put(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s);
|
|
/* Der Nachbar soll dieselbe Antwort nicht noch einmal bezahlen. Der Aufruf
|
|
* kehrt sofort zurück; ein nicht erreichbarer Nachbar kostet hier nichts. */
|
|
j_mesh_store(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s);
|
|
free(headcopy);
|
|
}
|
|
double now_ms = (now_s() - req_started) * 1000.0;
|
|
reqlog_append(vkey_name, (as_model && as_model[0]) ? as_model : rq_model,
|
|
ep->name, r.status, now_ms, upstream_part(now_ms), t_queue_ms,
|
|
t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached,
|
|
l_cost >= 0 ? l_cost : 0.0);
|
|
int rc = send_head(client, r.status, r.reason, &r.hdrs, (long)body_len, err, errlen);
|
|
if (rc == 0 && body_len && j_conn_write(client, body, body_len, err, errlen) < 0)
|
|
rc = -1;
|
|
free(body);
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return rc == 0 ? 0 : -2;
|
|
}
|
|
|
|
if (!head_sent &&
|
|
send_head(client, r.status, r.reason, &r.hdrs, r.chunked ? -2 : r.content_length,
|
|
err, errlen)) {
|
|
t_heartbeat = NULL;
|
|
if (!err[0]) snprintf(err, errlen, "client_write_failed");
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
return -2;
|
|
}
|
|
size_t pre_off = r.body_off;
|
|
size_t pre_len = r.buf.len > pre_off ? r.buf.len - pre_off : 0;
|
|
int rc = r.chunked
|
|
? relay_dechunk(client, &up, r.buf.data + pre_off, pre_len, ep->idle_timeout_s, deadline)
|
|
: relay_stream(client, &up, r.buf.data + pre_off, pre_len, r.content_length,
|
|
ep->idle_timeout_s, deadline);
|
|
{
|
|
/* Ein Strom lässt sich nicht nachträglich abrechnen; die Zeile sagt trotzdem,
|
|
* dass die Anfrage bedient wurde — mit Nullen statt mit Schätzungen. */
|
|
double now_ms = (now_s() - req_started) * 1000.0;
|
|
reqlog_append(vkey_name, (as_model && as_model[0]) ? as_model : rq_model,
|
|
ep->name, r.status, now_ms, upstream_part(now_ms), t_queue_ms,
|
|
t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached,
|
|
l_cost >= 0 ? l_cost : 0.0);
|
|
}
|
|
t_heartbeat = NULL;
|
|
resp_free(&r);
|
|
j_conn_close(&up);
|
|
free(body_alloc);
|
|
if (rc) {
|
|
/* -2 comes from the write to the client, -1 from the upstream. The
|
|
* distinction decides whether the box or the caller went away. */
|
|
snprintf(err, errlen, rc == -2 ? "client_write_failed" : "upstream_read_failed");
|
|
return -2;
|
|
}
|
|
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, const char *vkey_name,
|
|
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;
|
|
/* Der Anbieter hat gesagt, wann es wieder geht — dann wird nicht geraten,
|
|
* sondern gewartet, gedeckelt durch retry_max_wait: eine Stunde zu warten
|
|
* wäre keine Wiederholung mehr, sondern ein Ausfall mit Ansage. */
|
|
if (t_retry_after_s > 0 && (double)t_retry_after_s > nap_s) {
|
|
nap_s = (double)t_retry_after_s;
|
|
if (CFG.retry_max_wait_s > 0 && nap_s > CFG.retry_max_wait_s)
|
|
nap_s = CFG.retry_max_wait_s;
|
|
}
|
|
jlog("retry", "endpoint=%s attempt=%d keys=%d backoff_ms=%.0f retry_after_s=%d reason=%s",
|
|
ep->name, a + 1, ep->key_env_count, nap_s * 1000.0, t_retry_after_s, 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++;
|
|
t_req_retries++;
|
|
}
|
|
rc = forward_step(client, ep, rq, body, len, as_model, rq_model, cache_state,
|
|
started, head_sent, vkey_name, err, errlen);
|
|
if (rc == 0 || rc == -2) return rc;
|
|
if (!err_retryable(err)) return rc;
|
|
}
|
|
/* The provider named a reset time and all retries failed. Bench the endpoint
|
|
* until then for the following requests too; the per-request retry above is
|
|
* already over. */
|
|
if (rc != 0 && rc != -2 && !head_sent && t_retry_after_s > 0) {
|
|
STATE_LOCK();
|
|
double until = now_s() + (double)t_retry_after_s;
|
|
if (until > ep->cooldown_until) ep->cooldown_until = until;
|
|
STATE_UNLOCK();
|
|
jlog("cooldown", "endpoint=%s reason=retry_after reset_s=%d",
|
|
ep->name, t_retry_after_s);
|
|
}
|
|
return rc;
|
|
}
|
|
|
|
/* --------------------------------------------------------------- connection */
|
|
static int request_is_cacheable(const j_req *rq, char *why, size_t whylen)
|
|
{
|
|
if (CFG.cache_ttl_s <= 0) { snprintf(why, whylen, "disabled"); return 0; }
|
|
if (!rq->body) { snprintf(why, whylen, "no_body"); return 0; }
|
|
if (json_bool_value(rq->body, "stream")) { snprintf(why, whylen, "stream"); return 0; }
|
|
char cc[J_HDR_VALUE];
|
|
if (!j_hdrs_find(&rq->hdrs, "Cache-Control", cc, sizeof cc) &&
|
|
(strstr(cc, "no-cache") || strstr(cc, "no-store"))) {
|
|
snprintf(why, whylen, "client_no_cache");
|
|
return 0;
|
|
}
|
|
|
|
/* Eine Antwort mit Temperatur über null ist nicht reproduzierbar. Sie
|
|
* zwischenzuspeichern hieße, dem zweiten Fragesteller eine fremde Antwort zu geben —
|
|
* das ist keine Ersparnis, das ist eine falsche Antwort. Einbetter sind ausgenommen:
|
|
* sie liefern für denselben Text immer denselben Vektor. */
|
|
if (CFG.cache_deterministic_only) {
|
|
/* Eine Modell-Liste enthält keine Zufälligkeit: sie ist entweder da oder nicht. */
|
|
if (strstr(rq->path, "/models")) return 1;
|
|
if (strstr(rq->path, "embedding")) return 1;
|
|
double temp = 0;
|
|
int found = json_num_value(rq->body, "temperature", &temp);
|
|
if (found != 1) {
|
|
snprintf(why, whylen, "temperature_unknown");
|
|
return 0;
|
|
}
|
|
if (temp > 0.0) {
|
|
snprintf(why, whylen, "temperature_gt_zero");
|
|
return 0;
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
/* Der gespeicherte Kopf beginnt mit "HTTP/1.1 <code> …". Für die Logzeile braucht es
|
|
* den Code, und Raten wäre eine Behauptung. */
|
|
static int status_from_head(const char *head, size_t head_len)
|
|
{
|
|
if (!head || head_len < 13) return 200;
|
|
const char *sp = memchr(head, ' ', head_len);
|
|
if (!sp) return 200;
|
|
int code = 0;
|
|
for (const char *p = sp + 1; p < head + head_len && *p >= '0' && *p <= '9'; p++)
|
|
code = code * 10 + (*p - '0');
|
|
return code > 0 ? code : 200;
|
|
}
|
|
|
|
static void serve_from_cache(j_conn *client, const char *head, size_t head_len,
|
|
const char *body, size_t body_len, const char *path,
|
|
const char *model, double age)
|
|
{
|
|
char err[192];
|
|
char *out = malloc(head_len + 64);
|
|
if (!out) return;
|
|
size_t used = 0;
|
|
memcpy(out, head, head_len);
|
|
used = head_len;
|
|
/* rewrite the cache marker: stored heads say "miss", a hit must say "hit" */
|
|
char *marker = strstr(out, "X-Junction-Cache:");
|
|
if (marker) {
|
|
char *eol = strstr(marker, "\r\n");
|
|
if (eol) {
|
|
static const char hit[] = "X-Junction-Cache: hit\r\n";
|
|
size_t tail = used - (size_t)(eol + 2 - out);
|
|
memmove(marker + sizeof hit - 1, eol + 2, tail);
|
|
memcpy(marker, hit, sizeof hit - 1);
|
|
used = (size_t)(marker - out) + (sizeof hit - 1) + tail;
|
|
}
|
|
}
|
|
if (j_conn_write(client, out, used, err, sizeof err) >= 0 && body_len)
|
|
(void)j_conn_write(client, body, body_len, err, sizeof err);
|
|
free(out);
|
|
jlog("cache_hit", "path=%s model=%s age_s=%.0f bytes=%zu", path, model, age, body_len);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ mcp access */
|
|
/*
|
|
* /mcp ist kein Modellpfad: dort werden Aufgaben angelegt, Skills geändert, Erinnerungen
|
|
* und Wiki-Seiten geschrieben. Ein Port, der nur Modelle vermittelt, kann offen sein —
|
|
* dieser nicht. Also: von einem anderen Rechner nur mit einem Schlüssel, den junction
|
|
* selbst ausgegeben hat (mcp_auth auto, die Vorgabe).
|
|
*/
|
|
static int peer_is_local(const j_conn *c)
|
|
{
|
|
struct sockaddr_storage ss;
|
|
socklen_t len = sizeof ss;
|
|
|
|
if (c == NULL || c->fd < 0)
|
|
return 0;
|
|
if (getpeername(c->fd, (struct sockaddr *)&ss, &len) != 0)
|
|
return 0;
|
|
if (ss.ss_family == AF_UNIX)
|
|
return 1;
|
|
if (ss.ss_family == AF_INET) {
|
|
const struct sockaddr_in *a = (const struct sockaddr_in *)&ss;
|
|
|
|
return (ntohl(a->sin_addr.s_addr) >> 24) == 127;
|
|
}
|
|
if (ss.ss_family == AF_INET6) {
|
|
const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)&ss;
|
|
|
|
return IN6_IS_ADDR_LOOPBACK(&a6->sin6_addr) != 0;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* 401 ohne Weiteres: der Aufrufer soll wissen, dass ihm ein Schlüssel fehlt, und nicht
|
|
* rätseln, ob junction kaputt ist. */
|
|
static void send_mcp_unauthorized(j_conn *c)
|
|
{
|
|
const char *body = "{\"error\":\"mcp_key_required\",\"hint\":\"Authorization: Bearer "
|
|
"<vkey> - /mcp can write tasks, skills, memories and wiki pages\"}";
|
|
char hdr[512];
|
|
int n = snprintf(hdr, sizeof hdr,
|
|
"HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\n"
|
|
"WWW-Authenticate: Bearer realm=\"junction-mcp\"\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n", strlen(body));
|
|
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);
|
|
}
|
|
|
|
/* A client that knows its conversation can name it; otherwise the judge falls
|
|
* back to the stable beginning of the body. The junction header wins, so a
|
|
* constant provider header cannot merge two conversations. */
|
|
static const char *request_session(const j_hdrs *h, char *buf, size_t buflen)
|
|
{
|
|
static const char *const names[] = {
|
|
"x-junction-session", "x-session-id", "x-conversation-id", "x-opencode-session"
|
|
};
|
|
for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) {
|
|
if (j_hdrs_find(h, names[i], buf, buflen) == 0 && buf[0] != '\0')
|
|
return buf;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
static void handle_client(j_conn *client)
|
|
{
|
|
j_buf buf;
|
|
uint64_t ckey = 0; /* oben, weil 'goto done' die Initialisierung überspringt */
|
|
char *judge_body = NULL; /* dito: 'done' gibt ihn frei */
|
|
size_t judge_len = 0;
|
|
int flight_leader = 0;
|
|
j_buf_init(&buf);
|
|
j_req rq;
|
|
char err[512] = "";
|
|
if (read_request(client, &buf, &rq, err, sizeof err)) {
|
|
if (!strcmp(err, "body_too_large"))
|
|
send_simple(client, 413, "Payload Too Large", "{\"error\":\"body_too_large\"}");
|
|
else if (strcmp(err, "eof_in_headers") && strcmp(err, "timeout_waiting_headers") &&
|
|
!strstr(err, "eof_in"))
|
|
send_simple(client, 400, "Bad Request", "{\"error\":\"bad_request\"}");
|
|
j_buf_free(&buf);
|
|
return;
|
|
}
|
|
|
|
if (!strcmp(rq.path, "/status") || !strcmp(rq.path, "/v1/status") ||
|
|
!strcmp(rq.path, "/v1/queue") || !strcmp(rq.path, "/queue")) {
|
|
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
|
|
* Spiel ist. */
|
|
{
|
|
int is_mcp = !strncmp(rq.path, "/mcp", 4);
|
|
int handled = 0;
|
|
if (is_mcp) {
|
|
int need_key = 0;
|
|
j_vkey *vk = NULL; /* bleibt NULL bei lokalem Zugriff ohne Schlüssel */
|
|
|
|
if (CFG.mcp_auth == J_MCP_AUTH_ALL)
|
|
need_key = 1;
|
|
else if (CFG.mcp_auth == J_MCP_AUTH_AUTO && !peer_is_local(client))
|
|
need_key = 1;
|
|
|
|
if (need_key) {
|
|
const char *auth = NULL;
|
|
for (int i = 0; i < rq.hdrs.n; i++)
|
|
if (!strcasecmp(rq.hdrs.it[i].name, "Authorization"))
|
|
auth = rq.hdrs.it[i].value;
|
|
const char *bearer = (auth && !strncasecmp(auth, "Bearer ", 7)) ? auth + 7
|
|
: auth;
|
|
vk = vkey_lookup(&rq.hdrs, bearer);
|
|
if (vk == NULL) {
|
|
jlog("mcp_denied", "path=%.64s reason=mcp_key_required remote=%d",
|
|
rq.path, peer_is_local(client) ? 0 : 1);
|
|
send_mcp_unauthorized(client);
|
|
goto done;
|
|
}
|
|
}
|
|
handled = j_mcp_handle(&CFG, client, vk, rq.method, rq.path, rq.body, rq.body_len);
|
|
}
|
|
if (handled)
|
|
goto done;
|
|
}
|
|
|
|
/* Kürzen, bevor geschätzt wird: sonst entscheidet junction über einen Rumpf, den es
|
|
* gar nicht schickt. Der Kunde kann es pro Anfrage abschalten. */
|
|
char *comp_body = NULL;
|
|
size_t comp_len = 0;
|
|
jcomp_stats cstat;
|
|
memset(&cstat, 0, sizeof cstat);
|
|
int want_compress = (CFG.compress != J_COMPRESS_OFF);
|
|
for (int i = 0; i < CFG.endpoint_count; i++)
|
|
if (CFG.endpoints[i].compress == 1) want_compress = 1;
|
|
{
|
|
char hdr[16];
|
|
if (!j_hdrs_find(&rq.hdrs, "X-Junction-Compress", hdr, sizeof hdr) &&
|
|
(hdr[0] == '0' || !strncasecmp(hdr, "off", 3)))
|
|
want_compress = 0;
|
|
}
|
|
if (want_compress && rq.body_len) {
|
|
int rc = jcomp_messages(rq.body, rq.body_len, CFG.compress_keep,
|
|
(size_t)CFG.compress_min_bytes, &comp_body, &comp_len, &cstat);
|
|
if (rc == 1) {
|
|
jlog("compressed", "in=%zu out=%zu messages=%d replaced=%d keep=%d",
|
|
cstat.bytes_in, cstat.bytes_out, cstat.messages, cstat.replaced,
|
|
CFG.compress_keep);
|
|
/* Der Originalrumpf bleibt stehen: welches Ziel was bekommt, entscheidet
|
|
* sich erst bei der Auswahl. */
|
|
}
|
|
}
|
|
|
|
long need = declared_max_tokens(rq.body);
|
|
long ctx = estimate_ctx_tokens(rq.body, rq.body_len, CFG.ctx_chars_per_token);
|
|
long ctx_short = (comp_body && CFG.ctx_chars_per_token > 0)
|
|
? estimate_ctx_tokens(comp_body, comp_len, CFG.ctx_chars_per_token) : -1;
|
|
int has_image = body_has_image(rq.body);
|
|
char model[J_GLOB_MAX];
|
|
json_str_value(rq.body, "model", model, sizeof model);
|
|
|
|
/* Globale Modell-Politik: `models allow` ist eine Whitelist, sobald die erste
|
|
* Zeile existiert. /v1/models trägt kein Modell und wird nur gefiltert; jeder
|
|
* andere Aufruf mit einem Modell wird hier abgewiesen, bevor er einen Slot belegt. */
|
|
if (model[0] && strncmp(rq.path, "/v1/models", 10) != 0 && !j_model_allowed(model)) {
|
|
char emodel[256], refusal[512];
|
|
json_escape(model, emodel, sizeof emodel);
|
|
snprintf(refusal, sizeof refusal,
|
|
"{\"error\":\"model_not_allowed\",\"model\":\"%s\"}", emodel);
|
|
jlog("model_denied", "model=%s path=%s", model, rq.path);
|
|
send_simple(client, 403, "Forbidden", refusal);
|
|
goto done;
|
|
}
|
|
|
|
/* Virtual key: if the caller sent a key we minted, it may restrict the model
|
|
* and the endpoints. The real upstream key never reaches the client. */
|
|
j_vkey *vk = NULL;
|
|
{
|
|
const char *auth = NULL;
|
|
for (int i = 0; i < rq.hdrs.n; i++)
|
|
if (!strcasecmp(rq.hdrs.it[i].name, "Authorization")) auth = rq.hdrs.it[i].value;
|
|
const char *bearer = auth && !strncasecmp(auth, "Bearer ", 7) ? auth + 7 : auth;
|
|
vk = vkey_lookup(&rq.hdrs, bearer);
|
|
if (vk) {
|
|
/* Limits dieses Schlüssels, bevor irgendetwas Routen kostet. Das Fenster
|
|
* ist eine Minute, fest gerechnet (nicht gleitend): es soll einen Client
|
|
* bremsen, nicht auf die Millisekunde genau sein. */
|
|
int code = 0, retry_s = 0;
|
|
const char *reason = NULL;
|
|
double now = now_s();
|
|
STATE_LOCK();
|
|
if (vk->rpm > 0) {
|
|
if (vk->window_start <= 0 || now - vk->window_start >= 60.0) {
|
|
vk->window_start = now;
|
|
vk->window_hits = 0;
|
|
}
|
|
if (vk->window_hits >= vk->rpm) {
|
|
code = 429;
|
|
reason = "vkey_rate_limited";
|
|
retry_s = (int)(60.0 - (now - vk->window_start)) + 1;
|
|
} else {
|
|
vk->window_hits++;
|
|
}
|
|
}
|
|
if (!code && vk->budget_usd > 0 && vk->spent_usd >= vk->budget_usd) {
|
|
code = 403;
|
|
reason = "vkey_budget_exhausted";
|
|
}
|
|
if (code) vk->denied++; else vk->hits++;
|
|
double spent = vk->spent_usd;
|
|
STATE_UNLOCK();
|
|
if (code) {
|
|
jlog("vkey_limited", "vkey=%s reason=%s spent_usd=%.4f budget_usd=%.2f",
|
|
vk->name, reason, spent, vk->budget_usd);
|
|
send_limited(client, code, reason, (double)retry_s, vk->name);
|
|
goto done;
|
|
}
|
|
/* Nur pruefen, wenn wirklich ein Modell angefragt wird: /v1/models
|
|
* und andere Aufrufe ohne model-Feld tragen eine leere Zeichenkette und
|
|
* wuerden sonst an einem Glob wie "deepseek-*" scheitern. */
|
|
if (vk->allow[0] && model[0] && fnmatch(vk->allow, model, 0) != 0) {
|
|
char body[512], emodel[256], evk[128];
|
|
json_escape(model, emodel, sizeof emodel);
|
|
json_escape(vk->name, evk, sizeof evk);
|
|
snprintf(body, sizeof body,
|
|
"{\"error\":\"vkey_model_not_allowed\",\"vkey\":\"%s\",\"model\":\"%s\"}",
|
|
evk, emodel);
|
|
jlog("vkey_denied", "vkey=%s model=%s", vk->name, model);
|
|
send_simple(client, 403, "Forbidden", body);
|
|
goto done;
|
|
}
|
|
jlog("vkey", "vkey=%s model=%s", vk->name, model);
|
|
}
|
|
}
|
|
|
|
/* Waechter vor dem Routen: was nicht durchgehen soll, soll auch keinen Endpunkt
|
|
* belegen. Was durchgeht, entscheidet das Skript — junction bringt keine eigene
|
|
* Inhaltsregel mit und tut auch nicht so, als haette es eine. */
|
|
if (CFG.guard_cmd[0]) {
|
|
char greason[512] = "";
|
|
if (guard_run(CFG.guard_cmd, rq.body, rq.body_len, rq.path, model,
|
|
vk ? vk->name : "", greason, sizeof greason) != 0) {
|
|
char gbody[768], ger[512];
|
|
json_escape(greason, ger, sizeof ger);
|
|
snprintf(gbody, sizeof gbody,
|
|
"{\"error\":\"guard_refused\",\"reason\":\"%s\"}", ger);
|
|
g_guard_refused++;
|
|
jlog("guard_refused", "path=%s model=%s reason=%s", rq.path, model, greason);
|
|
send_simple(client, 403, "Forbidden", gbody);
|
|
goto done;
|
|
}
|
|
jlog("guard_pass", "path=%s model=%s", rq.path, model);
|
|
}
|
|
|
|
j_rule rule_copy;
|
|
j_rule *rule = first_matching_rule(rq.path, model, need, ctx, has_image, &rule_copy)
|
|
? &rule_copy : NULL;
|
|
if (!rule) {
|
|
char body[1024], epath[512], emodel[256];
|
|
json_escape(rq.path, epath, sizeof epath);
|
|
json_escape(model, emodel, sizeof emodel);
|
|
snprintf(body, sizeof body,
|
|
"{\"error\":\"no_matching_rule\",\"path\":\"%s\",\"model\":\"%s\","
|
|
"\"need_tokens\":%ld,\"ctx_tokens\":%ld,\"image\":%s}",
|
|
epath, emodel, need, ctx, has_image ? "true" : "false");
|
|
send_simple(client, 503, "Service Unavailable", body);
|
|
goto done;
|
|
}
|
|
if (rule->block) {
|
|
char body[1024], emodel[256];
|
|
json_escape(model, emodel, sizeof emodel);
|
|
snprintf(body, sizeof body, "{\"error\":\"blocked_by_rule\",\"line\":%d,\"model\":\"%s\"}",
|
|
rule->line, emodel);
|
|
jlog("blocked", "line=%d model=%s", rule->line, model);
|
|
send_simple(client, 403, "Forbidden", body);
|
|
goto done;
|
|
}
|
|
|
|
/* If no target of this rule can hold ctx + need, try the configured fallback
|
|
* pool instead of returning 503. The fallback pool's members carry their own
|
|
* "as" (usually deepseek-v4.1-flash); ctx_fallback_model is the fallback for
|
|
* members without one. */
|
|
int ctx_fallback_used = 0;
|
|
if (CFG.ctx_fallback[0] && ctx >= 0) {
|
|
int fits = 0;
|
|
for (int t = 0; t < rule_copy.target_count && !fits; t++) {
|
|
j_endpoint *e = NULL;
|
|
for (int i = 0; i < CFG.endpoint_count; i++)
|
|
if (!strcmp(CFG.endpoints[i].name, rule_copy.targets[t])) {
|
|
e = &CFG.endpoints[i];
|
|
break;
|
|
}
|
|
if (!e) continue;
|
|
const char *em = rule_copy.target_as[t][0] ? rule_copy.target_as[t] : model;
|
|
long mctx = j_models_limit(e, em, 0);
|
|
long mout = j_models_limit(e, em, 1);
|
|
long ep_ctx = mctx > 0 ? mctx : e->context;
|
|
long budget = need >= 0 ? need : 0;
|
|
if (mout > 0 && budget > mout) budget = mout;
|
|
int ep_compresses = (e->compress >= 0) ? e->compress : (CFG.compress != J_COMPRESS_OFF);
|
|
long ctx_here = (ep_compresses && ctx_short >= 0) ? ctx_short : ctx;
|
|
long total = ctx_here + budget;
|
|
if (ep_ctx <= 0 || total <= ep_ctx) fits = 1;
|
|
}
|
|
if (!fits) {
|
|
const j_pool *fb = find_pool(CFG.ctx_fallback);
|
|
if (fb && fb->count > 0) {
|
|
rule_copy.target_count = fb->count;
|
|
rule_copy.check = J_CHECK_NONE;
|
|
rule_copy.balance = J_BALANCE_FIRST;
|
|
rule_copy.strip[0] = '\0';
|
|
for (int c = 0; c < fb->count; c++) {
|
|
snprintf(rule_copy.targets[c], sizeof rule_copy.targets[c],
|
|
"%s", fb->targets[c]);
|
|
const char *m = fb->target_as[c][0] ? fb->target_as[c]
|
|
: CFG.ctx_fallback_model;
|
|
snprintf(rule_copy.target_as[c], sizeof rule_copy.target_as[c],
|
|
"%s", m);
|
|
}
|
|
jlog("ctx_fallback", "rule_line=%d ctx=%ld need=%ld pool=%s",
|
|
rule_copy.line, ctx, need, CFG.ctx_fallback);
|
|
ctx_fallback_used = 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Sampled escalation: every Nth request of a conversation goes to the judge.
|
|
* The judge is inserted in front of the rule's targets, so a failure (429,
|
|
* offline, budget) still falls back to the worker instead of failing the turn.
|
|
* An oversized context already moved to ctx_fallback; leave that decision alone. */
|
|
int judge_turn = 0;
|
|
if (rule->judge_every > 0 && !ctx_fallback_used && rq.body && model[0]) {
|
|
char sess[J_HDR_VALUE];
|
|
const char *session = request_session(&rq.hdrs, sess, sizeof sess);
|
|
uint64_t conversation = j_judge_conversation(rq.body, vk ? vk->name : "", session);
|
|
if (j_judge_tick(conversation, rule->line, rule->judge_every)) {
|
|
if (rule_copy.target_count + 1 > J_MAX_TARGETS) {
|
|
jlog("judge_skipped", "rule_line=%d reason=target_limit", rule->line);
|
|
} else {
|
|
if (rule->judge_cache > 0 &&
|
|
j_judge_cache_body(rq.body, rule->judge_cache == 2,
|
|
&judge_body, &judge_len) != 0) {
|
|
judge_body = NULL;
|
|
judge_len = 0;
|
|
}
|
|
for (int k = rule_copy.target_count; k > 0; k--) {
|
|
snprintf(rule_copy.targets[k], sizeof rule_copy.targets[k], "%s",
|
|
rule_copy.targets[k - 1]);
|
|
snprintf(rule_copy.target_as[k], sizeof rule_copy.target_as[k], "%s",
|
|
rule_copy.target_as[k - 1]);
|
|
}
|
|
snprintf(rule_copy.targets[0], sizeof rule_copy.targets[0], "%.*s",
|
|
(int)sizeof rule_copy.targets[0] - 1, rule->judge_target);
|
|
snprintf(rule_copy.target_as[0], sizeof rule_copy.target_as[0], "%.*s",
|
|
(int)sizeof rule_copy.target_as[0] - 1, rule->judge_as);
|
|
rule_copy.target_count++;
|
|
rule_copy.balance = J_BALANCE_FIRST;
|
|
judge_turn = 1;
|
|
jlog("judge", "rule_line=%d every=%d endpoint=%s model=%s cache=%s "
|
|
"conv=%016llx",
|
|
rule->line, rule->judge_every, rule->judge_target, rule->judge_as,
|
|
judge_body ? (rule->judge_cache == 2 ? "1h" : "5m") : "off",
|
|
(unsigned long long)conversation);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* The body goes out unchanged; a target that needs a different model name does
|
|
* that rewrite itself (forward_step), so a rule may mix targets with and
|
|
* without a rewrite. */
|
|
const char *out_body = rq.body;
|
|
size_t out_len = out_body ? strlen(out_body) : 0;
|
|
double started = now_s();
|
|
t_queue_ms = 0;
|
|
t_req_retries = 0;
|
|
t_rule_line = 0;
|
|
|
|
/* Does the caller want a stream? Then it gets a stream immediately — with nothing
|
|
* but comments in it until there is a real answer. Everything else waits silently
|
|
* and keeps its honest status code. */
|
|
char accept[J_HDR_VALUE];
|
|
int streaming = json_bool_value(rq.body, "stream") ||
|
|
(!j_hdrs_find(&rq.hdrs, "Accept", accept, sizeof accept) &&
|
|
strstr(accept, "text/event-stream") != NULL);
|
|
int head_sent = 0;
|
|
if (streaming && sse_open(client)) {
|
|
free(rq.body);
|
|
j_buf_free(&buf);
|
|
return;
|
|
}
|
|
if (streaming) head_sent = 1;
|
|
|
|
/* a rewritten body must be cached under the model it is actually sent as */
|
|
/* Mit zwei möglichen Rümpfen wäre ein Treffer nicht eindeutig: die Antwort auf den
|
|
* gekürzten Text kann sich von der auf den vollen unterscheiden. Also nicht cachen. */
|
|
/* A judge turn must not be answered from the worker's cache: same request,
|
|
* different model. */
|
|
int may_cache = (comp_body || judge_turn) ? 0
|
|
: request_is_cacheable(&rq, err, sizeof err);
|
|
if (may_cache) {
|
|
ckey = j_cache_key(rq.method, rq.path, model, out_body, out_len);
|
|
const char *head = NULL, *cbody = NULL;
|
|
size_t head_len = 0, cbody_len = 0;
|
|
double age = 0;
|
|
if (j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) {
|
|
/* Der Code muss gelesen werden, solange der Zeiger gilt: ein anderer Faden
|
|
* kann den Eintrag während des Sendens ersetzen, und dann zeigt `head` auf
|
|
* freigegebenen Speicher. */
|
|
int cstatus = status_from_head(head, head_len);
|
|
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age);
|
|
reqlog_append(vk ? vk->name : "", model, "", cstatus,
|
|
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
|
|
"hit", t_req_retries, 0, 0, 0, 0.0);
|
|
goto done;
|
|
}
|
|
/* Lokal nichts — aber vielleicht hat ein anderer Knoten dieselbe Frage schon
|
|
* beantwortet. Ein Treffer spart den Aufruf beim Anbieter; ein Fehlschlag
|
|
* kostet nur den kurzen Zeitablauf. */
|
|
{
|
|
char *mhead = NULL, *mbody = NULL;
|
|
size_t mhl = 0, mbl = 0;
|
|
double mage = 0;
|
|
if (j_mesh_lookup(ckey, &mhead, &mhl, &mbody, &mbl, &mage) == 0) {
|
|
int pstatus = status_from_head(mhead, mhl);
|
|
jlog("cache_hit", "path=%s model=%s age_s=%.0f via=peer", rq.path, model, mage);
|
|
serve_from_cache(client, mhead, mhl, mbody, mbl, rq.path, model, mage);
|
|
reqlog_append(vk ? vk->name : "", model, "", pstatus,
|
|
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
|
|
"peer", t_req_retries, 0, 0, 0, 0.0);
|
|
free(mhead);
|
|
free(mbody);
|
|
goto done;
|
|
}
|
|
}
|
|
|
|
/* Läuft dieselbe Anfrage schon? Dann warten und ihr Ergebnis mitbenutzen,
|
|
* statt ein zweites Mal zu bezahlen. */
|
|
flight_leader = j_cache_flight_begin(ckey);
|
|
if (!flight_leader) {
|
|
if (j_cache_flight_wait(ckey, 180.0) == 0 &&
|
|
j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) {
|
|
int jstatus = status_from_head(head, head_len);
|
|
jlog("flight_joined", "path=%s model=%s age_s=%.1f", rq.path, model, age);
|
|
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age);
|
|
reqlog_append(vk ? vk->name : "", model, "", jstatus,
|
|
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
|
|
"joined", t_req_retries, 0, 0, 0, 0.0);
|
|
goto done;
|
|
}
|
|
/* Der Führende ist gescheitert — dann selbst fragen. */
|
|
flight_leader = j_cache_flight_begin(ckey);
|
|
}
|
|
}
|
|
|
|
/* Ist die ganze Kette gerade offline oder im Cooldown, ist ein sofortiges 503 die
|
|
* falsche Antwort: im Van kommt der Uplink oft in Sekunden zurück. offline_wait sagt,
|
|
* wie lange ein Request darauf warten darf — bewusst VOR slot_acquire, denn ein
|
|
* Wartender soll keinen Upstream-Platz belegen. */
|
|
if (CFG.offline_wait_s > 0 && !head_sent) {
|
|
double until = now_s() + CFG.offline_wait_s;
|
|
int announced = 0;
|
|
for (;;) {
|
|
double t = now_s();
|
|
int usable = 0, offline = 0;
|
|
STATE_LOCK();
|
|
for (int tt = 0; tt < rule->target_count; tt++) {
|
|
if (vk && !vkey_allows_endpoint(vk, rule->targets[tt])) continue;
|
|
j_endpoint *e = NULL;
|
|
for (int i = 0; i < CFG.endpoint_count; i++)
|
|
if (!strcmp(CFG.endpoints[i].name, rule->targets[tt])) {
|
|
e = &CFG.endpoints[i];
|
|
break;
|
|
}
|
|
if (!e || e->paused) continue;
|
|
if (e->offline_until > t || e->cooldown_until > t) { offline++; continue; }
|
|
usable++;
|
|
}
|
|
STATE_UNLOCK();
|
|
if (usable > 0 || offline == 0 || t >= until) break;
|
|
if (!announced) {
|
|
jlog("offline_wait", "rule_line=%d offline_targets=%d wait_s=%.0f",
|
|
rule->line, offline, CFG.offline_wait_s);
|
|
g_offline_waits++;
|
|
announced = 1;
|
|
}
|
|
struct timespec nap = { .tv_sec = 0, .tv_nsec = 100 * 1000 * 1000 };
|
|
nanosleep(&nap, NULL);
|
|
}
|
|
}
|
|
|
|
double queue_started = now_s();
|
|
/* `strip "local/"`: der Client darf local/qwen3.6-35b verlangen, die Box bekommt
|
|
* qwen3.6-35b. Das Präfix ist eine Adresse, kein Modellname — es fällt hier weg,
|
|
* bevor irgendetwas weitergeleitet, bepreist oder geloggt wird. */
|
|
const char *eff_model = model;
|
|
{
|
|
size_t sl = strlen(rule->strip);
|
|
if (sl && !strncmp(model, rule->strip, sl)) eff_model = model + sl;
|
|
}
|
|
|
|
int slot_rc = slot_acquire(client, head_sent, CFG.queue_timeout_s,
|
|
streaming ? "stream" : "request");
|
|
t_queue_ms = (long)((now_s() - queue_started) * 1000.0);
|
|
if (slot_rc != 0) {
|
|
if (!head_sent) {
|
|
char body[512];
|
|
snprintf(body, sizeof body,
|
|
"{\"error\":\"queue_timeout\",\"max_inflight\":%d,"
|
|
"\"queue_timeout_s\":%.0f,\"rule_line\":%d,"
|
|
"\"retry_after_s\":%.0f}",
|
|
CFG.max_inflight, CFG.queue_timeout_s, rule->line, estimated_wait_s());
|
|
/* Standard-Header, damit Clients (auch ohne Polling) wissen, wann
|
|
* sie es erneut versuchen sollten: Retry-After (RFC 7231) plus
|
|
* X-Estimated-Wait-Time als Sekunden fuer eigene Anzeigen. */
|
|
double eta = estimated_wait_s();
|
|
char hdr[1024];
|
|
int hn = snprintf(hdr, sizeof hdr,
|
|
"HTTP/1.1 503 Service Unavailable\r\n"
|
|
"Content-Type: application/json\r\n"
|
|
"Retry-After: %.0f\r\n"
|
|
"X-Estimated-Wait-Time: %.0f\r\n"
|
|
"Content-Length: %zu\r\nConnection: close\r\n\r\n",
|
|
eta, eta, strlen(body));
|
|
char werr[128];
|
|
if (j_conn_write(client, hdr, (size_t)hn, werr, sizeof werr) >= 0)
|
|
(void)j_conn_write(client, body, strlen(body), werr, sizeof werr);
|
|
jlog("queue_timeout", "path=%s max_inflight=%d retry_after=%.0f", rq.path, CFG.max_inflight, eta);
|
|
}
|
|
j_buf_free(&buf);
|
|
free(rq.body);
|
|
return;
|
|
}
|
|
int slot_held = 1;
|
|
|
|
int order[J_MAX_TARGETS];
|
|
int norder = 0;
|
|
for (int t = 0; t < rule->target_count; t++) {
|
|
if (vk && !vkey_allows_endpoint(vk, rule->targets[t])) continue;
|
|
order[norder++] = t;
|
|
}
|
|
{
|
|
int mode = (rule->balance >= 0) ? rule->balance : CFG.balance;
|
|
if (mode != J_BALANCE_FIRST && norder > 1) balance_order(rule, order, norder);
|
|
}
|
|
|
|
char attempts[768] = "";
|
|
for (int oi = 0; oi < norder; oi++) {
|
|
int t = order[oi];
|
|
j_endpoint *ep = NULL;
|
|
for (int i = 0; i < CFG.endpoint_count; i++)
|
|
if (!strcmp(CFG.endpoints[i].name, rule->targets[t])) { ep = &CFG.endpoints[i]; break; }
|
|
if (!ep) continue;
|
|
|
|
STATE_LOCK();
|
|
int skip_paused = ep->paused;
|
|
/* /v1/models kostet keine Tokens — Budget-/Hard-Limit-Block nur auf
|
|
* token-erzeugenden Pfaden anwenden, damit Metadaten erreichbar bleiben. */
|
|
int token_free_path = !strncmp(rq.path, "/v1/models", 10);
|
|
int skip_budget = !token_free_path &&
|
|
((ep->budget_hard > 0 && ep->usage_ok && ep->usage_percent >= ep->budget_hard)
|
|
|| (ep->exhausted && ep->on_hard_skip));
|
|
int soft_delay = (ep->budget_soft > 0 && ep->usage_ok &&
|
|
ep->usage_percent >= ep->budget_soft) ? (int)ep->on_soft_delay_s : 0;
|
|
double pct_now = ep->usage_percent;
|
|
int skip_cooling = ep->cooldown_until > now_s();
|
|
/* Was der Endpunkt an Kontext braucht: die geschätzte Prompt-Größe plus das
|
|
* angeforderte Ausgabebudget. Vorher wurde nur das Ausgabebudget geprüft —
|
|
* ein 9k-Prompt mit 4k Ausgabe passte damit in einen 8k-Endpunkt. */
|
|
/* Ein Ziel, das kürzt, muss auch mit dem gekürzten Rumpf gemessen werden — sonst
|
|
* wird eine kleine Box abgelehnt, obwohl sie den Text problemlos fasst. */
|
|
int ep_compresses = (ep->compress >= 0) ? ep->compress : (CFG.compress != J_COMPRESS_OFF);
|
|
long ctx_here = (ep_compresses && ctx_short >= 0) ? ctx_short : ctx;
|
|
long need_total = need;
|
|
if (ctx_here >= 0) need_total = (need >= 0) ? ctx_here + need : ctx_here;
|
|
/* Die Grenze des *Modells* schlägt die des Endpunkts: ein Anbieter mit
|
|
* mehreren Modellen veröffentlicht pro Modell eine eigene Zahl. Ein "as"
|
|
* schreibt den Namen um, also gilt der Name, den der Endpunkt sieht. */
|
|
const char *ep_model = rule->target_as[t][0] ? rule->target_as[t] : eff_model;
|
|
long mctx = j_models_limit(ep, ep_model, 0);
|
|
long mout = j_models_limit(ep, ep_model, 1);
|
|
long ep_ctx = mctx > 0 ? mctx : ep->context;
|
|
/* Nie mehr Ausgabe anrechnen, als das Modell überhaupt erzeugen kann. */
|
|
long budget_here = (mout > 0 && need > mout) ? mout : need;
|
|
if (ctx_here >= 0) need_total = (budget_here >= 0) ? ctx_here + budget_here : ctx_here;
|
|
/* Unbekannt (0) heißt nicht "passt nicht": dann entscheidet der Endpunkt. */
|
|
int skip_context = (need_total >= 0 && ep_ctx > 0 && ep_ctx < need_total);
|
|
int skip_vision = (ep->vision == 0 && has_image);
|
|
int skip_offline = ep->offline_until > now_s();
|
|
STATE_UNLOCK();
|
|
if (skip_paused) { strncat(attempts, " paused", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
if (skip_budget) { strncat(attempts, " budget", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
if (skip_cooling) { strncat(attempts, " cooling", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
if (skip_vision) { strncat(attempts, " text-only", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
if (skip_context) { strncat(attempts, " context", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
if (skip_offline) { strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1); continue; }
|
|
|
|
int use_hooks = (rule->check == J_CHECK_HOOKS) ||
|
|
(rule->check == J_CHECK_INHERIT && ep->hook_count > 0);
|
|
double retry = rule->retry_s >= 0 ? rule->retry_s : ep->hook_retry_s;
|
|
int ready = wait_until_ready(ep, rq.path, model, need, retry, use_hooks);
|
|
if (ready != 0) {
|
|
jlog("hooks_failed", "endpoint=%s reason=%s", ep->name, ep->last_hook_reason);
|
|
strncat(attempts, " hooks", sizeof attempts - strlen(attempts) - 1);
|
|
continue;
|
|
}
|
|
|
|
if (!token_free_path && soft_delay > 0) {
|
|
jlog("soft_throttle", "endpoint=%s percent=%.1f delay_s=%d", ep->name, pct_now, soft_delay);
|
|
double until = now_s() + (double)soft_delay;
|
|
struct timespec nap = { .tv_sec = 0, .tv_nsec = 100 * 1000 * 1000 };
|
|
while (now_s() < until) nanosleep(&nap, NULL);
|
|
}
|
|
/* Ein Platz je (Endpunkt, Modell): eine Box, die dieses Modell geladen hält,
|
|
* bedient es einmal. Der Rest wartet hier — nicht in der Box. */
|
|
const char *gate_model = rule->target_as[t][0] ? rule->target_as[t] : eff_model;
|
|
int gate_on = ep->max_model_inflight > 0;
|
|
if (gate_on &&
|
|
model_gate_acquire(ep->name, gate_model, ep->max_model_inflight,
|
|
CFG.queue_timeout_s) != 0) {
|
|
jlog("model_queue_timeout", "endpoint=%s model=%s limit=%d wait_s=%.0f",
|
|
ep->name, gate_model, ep->max_model_inflight, CFG.queue_timeout_s);
|
|
snprintf(err, sizeof err, "model_busy_%s", ep->name);
|
|
strncat(attempts, " busy", sizeof attempts - strlen(attempts) - 1);
|
|
continue;
|
|
}
|
|
STATE_LOCK();
|
|
ep->inflight++;
|
|
STATE_UNLOCK();
|
|
if (!strcmp(ep->kind, "opencode")) {
|
|
/* Kein OpenAI-Protokoll: die Brücke übersetzt Anfrage und Antwort. */
|
|
int brc = opencode_serve(client, ep, &rq, rule->target_as[t][0] ? rule->target_as[t] : eff_model,
|
|
err, sizeof err);
|
|
STATE_LOCK();
|
|
ep->inflight--;
|
|
if (gate_on) model_gate_release(ep->name, gate_model, ep->max_model_inflight);
|
|
if (brc == 0) {
|
|
ep->ok_count++;
|
|
g_req_ok++;
|
|
STATE_UNLOCK();
|
|
if (slot_held) { slot_release(); slot_held = 0; }
|
|
jlog("served_by", "endpoint=%s bridge=opencode rule_line=%d", ep->name, rule->line);
|
|
goto done;
|
|
}
|
|
ep->fail_count++;
|
|
|
|
g_req_fail++;
|
|
snprintf(ep->last_error, sizeof ep->last_error, "%s", err);
|
|
STATE_UNLOCK();
|
|
jlog("failed", "endpoint=%s error=%s", ep->name, err);
|
|
strncat(attempts, " bridge", sizeof attempts - strlen(attempts) - 1);
|
|
continue;
|
|
}
|
|
/* Welcher Rumpf geht raus? Ein Ziel mit eigenem Kürzen bekommt den kurzen,
|
|
* ein großes den vollen. Der Judge bekommt den vollen Rumpf mit dem
|
|
* Cache-Marker; fällt er aus, sieht der Worker wieder den normalen Rumpf. */
|
|
int judge_target = judge_turn && t == 0;
|
|
int judge_body_used = judge_target && judge_body != NULL;
|
|
const char *send_body = judge_body_used ? judge_body
|
|
: ((ep_compresses && comp_body) ? comp_body : out_body);
|
|
size_t send_len = judge_body_used ? judge_len
|
|
: ((ep_compresses && comp_body) ? comp_len : out_len);
|
|
if (!judge_body_used && ep_compresses && comp_body) {
|
|
/* Erst hier zählen: gekürzt wird zwar für jede Anfrage vorbereitet, aber nur
|
|
* ein Ziel, das es will, bekommt den kurzen Text. Ein Zähler am Vorbereiten
|
|
* wäre eine Lüge über die Ersparnis. */
|
|
g_compress_reqs++;
|
|
g_compress_bytes_in += cstat.bytes_in;
|
|
g_compress_bytes_out += cstat.bytes_out;
|
|
}
|
|
t_rule_line = rule->line;
|
|
/* Ein "as" der Regel gewinnt; sonst muss ein abgeschnittenes Präfix den Rumpf
|
|
* umschreiben, sonst steht der Name nur im Router anders da als bei der Box. */
|
|
const char *send_model = rule->target_as[t][0] ? rule->target_as[t]
|
|
: (eff_model != model ? eff_model : "");
|
|
int rc = forward_with_retry(client, ep, &rq, send_body, send_len, send_model, eff_model,
|
|
may_cache ? "miss" : "off", started, head_sent,
|
|
vk ? vk->name : "", err, sizeof err);
|
|
STATE_LOCK();
|
|
ep->inflight--;
|
|
STATE_UNLOCK();
|
|
if (gate_on) model_gate_release(ep->name, gate_model, ep->max_model_inflight);
|
|
STATE_LOCK();
|
|
if (rc == 0) {
|
|
ep->ok_count++;
|
|
ep->last_ms = (long)((now_s() - started) * 1000.0);
|
|
ep->lat_bucket[lat_bucket_index((double)ep->last_ms / 1000.0)]++;
|
|
ep->lat_n++;
|
|
ep->lat_sum_s += (double)ep->last_ms / 1000.0;
|
|
g_req_ok++;
|
|
g_latency_ms_sum += (double)ep->last_ms;
|
|
g_latency_n++;
|
|
g_req_bytes += send_len;
|
|
STATE_UNLOCK();
|
|
if (slot_held) { slot_release(); slot_held = 0; }
|
|
jlog("served_by", "endpoint=%s ms=%ld need_tokens=%ld rule_line=%d tls=%d cache=%s",
|
|
ep->name, ep->last_ms, need, rule->line,
|
|
!strncmp(ep->base, "https://", 8), may_cache ? "miss" : "off");
|
|
goto done;
|
|
}
|
|
if (rc == -2) {
|
|
ep->fail_count++;
|
|
|
|
g_req_fail++;
|
|
snprintf(ep->last_error, sizeof ep->last_error, "%s", err);
|
|
STATE_UNLOCK();
|
|
jlog("aborted", "endpoint=%s error=%s", ep->name, err);
|
|
if (slot_held) { slot_release(); slot_held = 0; }
|
|
goto done;
|
|
}
|
|
ep->fail_count++;
|
|
|
|
g_req_fail++;
|
|
if (error_is_offline(err)) {
|
|
ep->offline_until = now_s() + CFG.offline_hold_s;
|
|
STATE_UNLOCK();
|
|
jlog("offline", "endpoint=%s reason=connect_failed hold_s=%.0f error=%s",
|
|
ep->name, CFG.offline_hold_s, err);
|
|
strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1);
|
|
} else {
|
|
double cool_until = now_s() + ep->cooldown_s;
|
|
if (cool_until > ep->cooldown_until) ep->cooldown_until = cool_until;
|
|
STATE_UNLOCK();
|
|
jlog("failed", "endpoint=%s error=%s", ep->name, err);
|
|
strncat(attempts, " failed", sizeof attempts - strlen(attempts) - 1);
|
|
}
|
|
}
|
|
|
|
if (slot_held) { slot_release(); slot_held = 0; }
|
|
if (head_sent) {
|
|
/* the caller holds a 200 by now, so the failure has to be an event */
|
|
char msg[512];
|
|
snprintf(msg, sizeof msg, "no endpoint available (need=%ld, ctx=%ld, rule line %d, tried:%s)",
|
|
need, ctx, rule->line, attempts[0] ? attempts : " none");
|
|
sse_error(client, 503, msg);
|
|
jlog("no_endpoint", "path=%s need=%ld ctx=%ld attempts=%s", rq.path, need, ctx,
|
|
attempts[0] ? attempts + 1 : "none");
|
|
} else {
|
|
char body[1024];
|
|
snprintf(body, sizeof body,
|
|
"{\"error\":\"no_endpoint_available\",\"need_tokens\":%ld,\"ctx_tokens\":%ld,"
|
|
"\"rule_line\":%d,\"attempts\":\"%s\"}",
|
|
need, ctx, rule->line, attempts[0] ? attempts + 1 : "none");
|
|
send_simple(client, 503, "Service Unavailable", body);
|
|
}
|
|
|
|
done:
|
|
if (flight_leader && ckey) j_cache_flight_end(ckey);
|
|
free(judge_body);
|
|
free(comp_body);
|
|
free(rq.body);
|
|
j_buf_free(&buf);
|
|
}
|
|
|
|
static int progress_log(const char *role, double idle_s)
|
|
{
|
|
jlog("still_working", "side=%s silent_s=%.1f", role, idle_s);
|
|
if (!t_heartbeat) return 0;
|
|
/* A caller that asked for a stream is entitled to hear something while the model
|
|
* thinks — otherwise a proxy with a 60 s read timeout kills a stream that is
|
|
* perfectly alive. Comment lines: parsers must ignore them. */
|
|
if (sse_comment(t_heartbeat, "junction: model is still working (%.0fs)",
|
|
now_s() - t_heartbeat_started) < 0)
|
|
return -1; /* client is gone; stop waiting for a model nobody listens to */
|
|
return 0;
|
|
}
|
|
|
|
static void *connection_thread(void *arg)
|
|
{
|
|
int cfd = *(int *)arg;
|
|
free(arg);
|
|
j_conn client = J_CONN_INIT;
|
|
char err[256];
|
|
if (CFG.listen_tls) {
|
|
if (j_tls_server_accept(&client, cfd, err, sizeof err)) {
|
|
jlog("tls_accept_failed", "%s", err);
|
|
close(cfd);
|
|
return NULL;
|
|
}
|
|
} else {
|
|
client.fd = cfd;
|
|
}
|
|
client.role = "client";
|
|
if (g_draining) {
|
|
send_restarting(&client);
|
|
} else {
|
|
handle_client(&client);
|
|
}
|
|
j_conn_close(&client);
|
|
return NULL;
|
|
}
|
|
|
|
/* ---------------------------------------------------------------------- main */
|
|
static int make_listener(const j_config *cfg, char *err, size_t errlen)
|
|
{
|
|
struct addrinfo hints, *res = NULL;
|
|
memset(&hints, 0, sizeof hints);
|
|
hints.ai_family = AF_UNSPEC;
|
|
hints.ai_socktype = SOCK_STREAM;
|
|
hints.ai_flags = AI_PASSIVE;
|
|
char portstr[16];
|
|
snprintf(portstr, sizeof portstr, "%d", cfg->listen_port);
|
|
if (getaddrinfo(cfg->listen_host, portstr, &hints, &res) != 0) {
|
|
snprintf(err, errlen, "cannot resolve %s:%d", cfg->listen_host, cfg->listen_port);
|
|
return -1;
|
|
}
|
|
int lfd = -1;
|
|
for (struct addrinfo *ai = res; ai; ai = ai->ai_next) {
|
|
lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
|
|
if (lfd < 0) continue;
|
|
int one = 1;
|
|
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
|
|
#ifdef SO_REUSEPORT
|
|
/* Mehrere Instanzen auf demselben Port: der Kernel verteilt die Verbindungen.
|
|
* Ohne das könnte eine neue Instanz erst binden, wenn die alte den Port
|
|
* aufgegeben hat — ein Rolling Update hätte dann ein Fenster ohne Bedienung. */
|
|
if (cfg->so_reuseport)
|
|
setsockopt(lfd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof one);
|
|
#endif
|
|
if (!bind(lfd, ai->ai_addr, ai->ai_addrlen) && !listen(lfd, 32)) break;
|
|
close(lfd);
|
|
lfd = -1;
|
|
}
|
|
freeaddrinfo(res);
|
|
if (lfd < 0) snprintf(err, errlen, "cannot listen on %s:%d: %s", cfg->listen_host,
|
|
cfg->listen_port, strerror(errno));
|
|
return lfd;
|
|
}
|
|
|
|
/* Erreichbarkeit im Hintergrund prüfen.
|
|
*
|
|
* Ein Anfragepfad soll nicht der erste sein, der merkt, dass eine Box weg ist: hier
|
|
* wird jeder Endpunkt alle probe_interval_s gefragt (GET <base>/models, kurzer
|
|
* Zeitablauf). Antwortet er nicht — kein TCP, kein HTTP —, geht er für offline_hold_s
|
|
* offline, und der nächste Lauf prüft weiter. Antwortet er wieder, ist er sofort
|
|
* zurück, ohne dass jemand eine Anfrage dafür verschwenden musste.
|
|
*
|
|
* 4xx zählt als erreichbar: ein 401 heißt "falscher Schlüssel", nicht "Maschine aus".
|
|
* Für den Router ist das ein anderer Fehler und gehört nicht hierher.
|
|
*/
|
|
static int probe_endpoint(const j_endpoint *ep)
|
|
{
|
|
char base[J_URL_MAX];
|
|
snprintf(base, sizeof base, "%s", ep->base);
|
|
size_t bl = strlen(base);
|
|
while (bl > 0 && base[bl - 1] == '/') base[--bl] = '\0';
|
|
if (!bl) return -1;
|
|
|
|
char cmd[2048];
|
|
int off = snprintf(cmd, sizeof cmd, "curl -s -o /dev/null -m %.0f ",
|
|
CFG.probe_timeout_s > 0 ? CFG.probe_timeout_s : 3.0);
|
|
/* Dieselbe Vertrauensfrage wie im Anfragepfad: ein Endpunkt mit tls_verify off wird
|
|
* auch hier nicht geprüft, und eine eigene CA gilt mit. */
|
|
if (!ep->tls_verify)
|
|
off += snprintf(cmd + off, sizeof cmd - (size_t)off, "-k ");
|
|
else if (ep->tls_ca[0])
|
|
off += snprintf(cmd + off, sizeof cmd - (size_t)off, "--cacert '%s' ", ep->tls_ca);
|
|
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);
|
|
for (int i = 0; i < ep->header_count && off > 0 && (size_t)off < sizeof cmd; i++) {
|
|
if (strchr(ep->headers[i], '\'')) continue;
|
|
off += snprintf(cmd + off, sizeof cmd - (size_t)off, "-H '%s' ", ep->headers[i]);
|
|
}
|
|
if (off <= 0 || (size_t)off >= sizeof cmd) return -1;
|
|
/* Zwei Zahlen: Statuscode und die Zeit bis zum TCP-Verbindungsaufbau. Nur die
|
|
* zweite beantwortet die Frage, um die es geht — ein Server, der langsam antwortet,
|
|
* hatte eine Verbindung; ein Host, der nicht antwortet, hatte keine. */
|
|
snprintf(cmd + off, sizeof cmd - (size_t)off,
|
|
"-w '%%{http_code} %%{time_connect}' '%s/models'", base);
|
|
|
|
FILE *f = popen(cmd, "r");
|
|
if (!f) return -1;
|
|
char out[64] = "";
|
|
if (!fgets(out, sizeof out, f)) out[0] = '\0';
|
|
(void)pclose(f);
|
|
|
|
/* "Offline" heißt: keine Verbindung zustande gekommen. Ein Server, der die TCP-
|
|
* Verbindung aufbaut und dann langsam antwortet, ist erreichbar — er rechnet nur.
|
|
* Wer hier jeden Zeitablauf als Ausfall wertet, nimmt langsame Endpunkte dauerhaft
|
|
* aus dem Verkehr (der Stub mit 6 s Antwortzeit ist genau dieser Fall). */
|
|
double t_connect = 0.0;
|
|
if (sscanf(out, "%*d %lf", &t_connect) != 1) t_connect = 0.0;
|
|
return t_connect > 0.0 ? 0 : -1;
|
|
}
|
|
|
|
static void *probe_thread(void *unused)
|
|
{
|
|
(void)unused;
|
|
for (;;) {
|
|
double t = now_s();
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
j_endpoint *ep = &CFG.endpoints[i];
|
|
if (!ep->probe_on || ep->paused || !ep->base[0]) continue;
|
|
int alive = probe_endpoint(ep) == 0;
|
|
int was_off = ep->offline_until > now_s();
|
|
STATE_LOCK();
|
|
if (!alive) {
|
|
double hold = CFG.offline_hold_s > 0 ? CFG.offline_hold_s : 20.0;
|
|
ep->offline_until = now_s() + hold;
|
|
} else {
|
|
ep->offline_until = 0;
|
|
ep->probe_ok = 1;
|
|
}
|
|
ep->probe_at = now_s();
|
|
STATE_UNLOCK();
|
|
if (!alive && !was_off)
|
|
jlog("probe_offline", "endpoint=%s base=%s hold_s=%.0f",
|
|
ep->name, ep->base, CFG.offline_hold_s);
|
|
else if (alive && was_off)
|
|
jlog("probe_recovered", "endpoint=%s", ep->name);
|
|
}
|
|
double nap = CFG.probe_interval_s > 0 ? CFG.probe_interval_s : 20.0;
|
|
double next = t + nap;
|
|
while (now_s() < next) {
|
|
struct timespec ts = { 0, 200 * 1000 * 1000 };
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
/* Startroutine des Hintergrundabrufs (models.c). */
|
|
static void *models_refresh_thread(void *unused)
|
|
{
|
|
(void)unused;
|
|
j_models_refresh_all();
|
|
return NULL;
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
const char *config_path = NULL;
|
|
int port_override = 0;
|
|
int check_only = 0;
|
|
for (int i = 1; i < argc; i++) {
|
|
if (!strcmp(argv[i], "--config") && i + 1 < argc) config_path = argv[++i];
|
|
else if (!strcmp(argv[i], "--port") && i + 1 < argc) port_override = atoi(argv[++i]);
|
|
else if (!strcmp(argv[i], "--check")) check_only = 1;
|
|
else {
|
|
fprintf(stderr, "usage: junction --config <file> [--port N] [--check]\n");
|
|
return 2;
|
|
}
|
|
}
|
|
if (!config_path) {
|
|
fprintf(stderr, "usage: junction --config <file> [--port N] [--check]\n");
|
|
return 2;
|
|
}
|
|
char err[512] = "";
|
|
if (j_config_load(config_path, &CFG, err, sizeof err)) {
|
|
fprintf(stderr, "config error: %s\n", err);
|
|
return 1;
|
|
}
|
|
/* --check: die Datei prüfen, ohne zu binden. Damit ist "vor dem Neustart
|
|
* einmal durch den Parser" ein Befehl und kein Handgriff in der Erinnerung. */
|
|
if (check_only) {
|
|
printf("config ok: %d endpoints, %d rules, %d vkeys, listen %s:%d%s\n",
|
|
CFG.endpoint_count, CFG.rule_count, CFG.vkey_count,
|
|
CFG.listen_host, CFG.listen_port, CFG.listen_tls ? " tls" : "");
|
|
return 0;
|
|
}
|
|
j_mcp_set_log(mcp_log_bridge);
|
|
g_started_at = now_s();
|
|
if (port_override) CFG.listen_port = port_override;
|
|
|
|
if (CFG.listen_tls) {
|
|
if (!j_tls_available()) {
|
|
fprintf(stderr, "config error: 'listen ... tls' needs a build with TLS support\n");
|
|
return 1;
|
|
}
|
|
if (j_tls_server_start(CFG.tls_cert, CFG.tls_key, err, sizeof err)) {
|
|
fprintf(stderr, "tls error: %s\n", err);
|
|
return 1;
|
|
}
|
|
}
|
|
for (int i = 0; i < CFG.endpoint_count; i++) {
|
|
if (!strncmp(CFG.endpoints[i].base, "https://", 8) && !j_tls_available()) {
|
|
fprintf(stderr, "config error: endpoint %s uses https but this build has no TLS\n",
|
|
CFG.endpoints[i].name);
|
|
return 1;
|
|
}
|
|
}
|
|
j_cache_config((size_t)CFG.cache_entries, (size_t)CFG.cache_bytes, CFG.cache_ttl_s);
|
|
|
|
/* Preise laden. Fehlt die Datei, läuft alles weiter — nur steht dann bei jeder
|
|
* Anfrage cost_usd=unknown statt einer erfundenen Null. */
|
|
{
|
|
char perr[256];
|
|
if (j_price_load(CFG.prices_path, perr, sizeof perr))
|
|
fprintf(stderr, "[%s] prices: %s (cost will be reported as unknown)\n",
|
|
CFG.log_prefix, perr);
|
|
else
|
|
fprintf(stderr, "[%s] prices loaded: %d models from %s\n",
|
|
CFG.log_prefix, j_price_count(), CFG.prices_path);
|
|
}
|
|
|
|
/* Welche Grenzen gelten, steht beim Anbieter, nicht in unserer Konfiguration:
|
|
* einmal je Endpunkt die Modellliste geholt -- im Hintergrund, siehe unten. */
|
|
|
|
signal(SIGPIPE, SIG_IGN);
|
|
/* Kein SA_RESTART: accept() soll mit EINTR zurückkommen, damit die Hauptschleife
|
|
* das Signal sieht. Ein Router, der auf einen abbauenden Client wartet, ist beim
|
|
* Herunterfahren nicht zu gebrauchen. */
|
|
{
|
|
struct sigaction sa;
|
|
memset(&sa, 0, sizeof sa);
|
|
sa.sa_handler = on_term;
|
|
sigemptyset(&sa.sa_mask);
|
|
sa.sa_flags = 0;
|
|
sigaction(SIGTERM, &sa, NULL);
|
|
sigaction(SIGINT, &sa, NULL);
|
|
}
|
|
j_set_progress(progress_log);
|
|
|
|
/* Budgets brauchen einen eigenen Faden: die Abfrage darf keinen Request aufhalten. */
|
|
{
|
|
int any_usage = 0;
|
|
for (int i = 0; i < CFG.endpoint_count; i++)
|
|
if (CFG.endpoints[i].usage_cmd[0] && CFG.endpoints[i].usage_poll_s > 0) any_usage = 1;
|
|
if (any_usage) {
|
|
pthread_t th;
|
|
pthread_attr_t attr;
|
|
pthread_attr_init(&attr);
|
|
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
|
pthread_create(&th, &attr, usage_thread, NULL);
|
|
pthread_attr_destroy(&attr);
|
|
jlog("usage_thread", "started endpoints_with_usage=%d", CFG.endpoint_count);
|
|
}
|
|
}
|
|
|
|
int lfd = make_listener(&CFG, err, sizeof err);
|
|
if (lfd < 0) {
|
|
fprintf(stderr, "%s\n", err);
|
|
return 1;
|
|
}
|
|
j_control_ops_install();
|
|
/* Monatsverbrauch der vkeys aus dem Spend-Log holen, bevor der erste Request
|
|
* kommt — sonst wäre jedes Budget nach einem Neustart wieder voll. */
|
|
spend_load();
|
|
/* 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);
|
|
}
|
|
if (CFG.probe_interval_s > 0) {
|
|
pthread_t pt;
|
|
if (pthread_create(&pt, NULL, probe_thread, NULL) == 0)
|
|
pthread_detach(pt);
|
|
jlog("probe", "interval_s=%.0f timeout_s=%.0f endpoints=%d", CFG.probe_interval_s,
|
|
CFG.probe_timeout_s, CFG.endpoint_count);
|
|
}
|
|
/* Gemeinsamer Cache: eigener Port für die Nachbarn, optional. Scheitert er, läuft
|
|
* der Router weiter — ein Cache ist eine Ersparnis, keine Bedingung. */
|
|
if (j_mesh_start())
|
|
jlog("cache_peer", "mesh active peers=%d port=%d", CFG.cache_peer_count,
|
|
CFG.cache_tcp_port);
|
|
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);
|
|
|
|
/* Welche Grenzen gelten, steht beim Anbieter, nicht in unserer Konfiguration.
|
|
* Der Abruf läuft im Hintergrund: ein langsamer Endpunkt darf den Start nicht
|
|
* aufhalten (ein Endpunkt mit 6 s Antwortzeit hieße sonst 6 s kein Listener).
|
|
* Bis die Liste da ist, gilt die Zahl aus dem Endpunkt-Block. */
|
|
{
|
|
pthread_t mt;
|
|
if (pthread_create(&mt, NULL, models_refresh_thread, NULL) == 0)
|
|
pthread_detach(mt);
|
|
else
|
|
j_models_refresh_all();
|
|
}
|
|
|
|
/* Neustart-Ankuendigung: nach SIGTERM bleibt der Listener noch eine kurze
|
|
* Gnadenfrist offen. Neue Requests bekommen 503 + Retry-After ("restarting"),
|
|
* laufende Requests duerfen fertig werden. Danach wird der Port geschlossen. */
|
|
double drain_started = 0.0;
|
|
const double restart_grace_s = 2.0;
|
|
for (;;) {
|
|
if (g_draining && drain_started == 0.0) {
|
|
drain_started = now_s();
|
|
jlog("restarting", "grace_s=%.1f inflight=%d", restart_grace_s, drain_inflight());
|
|
}
|
|
if (g_draining && drain_started > 0.0) {
|
|
double elapsed = now_s() - drain_started;
|
|
if (g_stop || (elapsed >= restart_grace_s && drain_inflight() == 0) ||
|
|
elapsed >= CFG.drain_timeout_s)
|
|
break;
|
|
}
|
|
struct pollfd pfd;
|
|
pfd.fd = lfd;
|
|
pfd.events = POLLIN;
|
|
pfd.revents = 0;
|
|
int pr = poll(&pfd, 1, 200);
|
|
if (pr < 0) {
|
|
if (errno == EINTR) continue;
|
|
break;
|
|
}
|
|
if (pr == 0) continue;
|
|
int cfd = accept(lfd, NULL, NULL);
|
|
if (cfd < 0) {
|
|
if (errno == EINTR) continue;
|
|
break;
|
|
}
|
|
int *arg = malloc(sizeof *arg);
|
|
if (!arg) { close(cfd); continue; }
|
|
*arg = cfd;
|
|
pthread_t th;
|
|
pthread_attr_t attr;
|
|
pthread_attr_init(&attr);
|
|
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
|
if (pthread_create(&th, &attr, connection_thread, arg) != 0) {
|
|
close(cfd);
|
|
free(arg);
|
|
}
|
|
pthread_attr_destroy(&attr);
|
|
}
|
|
close(lfd);
|
|
|
|
/* Drain: der Port ist aufgegeben, was schon läuft, darf fertig werden. Neue
|
|
* Verbindungen bekommt bei SO_REUSEPORT die nächste Instanz; ohne sie laufen sie
|
|
* ins Leere — deshalb gehört drain_timeout dazu und nicht in ein Handbuch. */
|
|
g_draining = 1;
|
|
int waiting = drain_inflight();
|
|
jlog("draining", "closed_listener inflight=%d timeout_s=%.1f", waiting,
|
|
CFG.drain_timeout_s);
|
|
double deadline = now_s() + CFG.drain_timeout_s;
|
|
while (drain_inflight() > 0 && now_s() < deadline) {
|
|
struct timespec ts = { 0, 50 * 1000 * 1000 };
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
j_mesh_stop();
|
|
int left = drain_inflight();
|
|
if (left > 0)
|
|
jlog("drain_timeout", "inflight=%d after_s=%.1f — beendet trotzdem",
|
|
left, CFG.drain_timeout_s);
|
|
else
|
|
jlog("drained", "inflight=0 waited_ok=1");
|
|
return 0;
|
|
}
|