Files
junction/tests/stub.c
T
Hermes 6bb63268f1 Retry-After auch als HTTP-Datum
RFC 7231 erlaubt beide Formen; junction las nur die Zahl. Jetzt wird auch das Datum
verstanden, und zwar über dieselbe Zivilrechnung wie der Monatswechsel: timegm ist nicht
POSIX, und eine Zeitzone hat in einer Wiederholungsentscheidung nichts zu suchen — die
Angabe ist immer GMT. Ein Datum in der Vergangenheit heißt "sofort", alles Unlesbare
zählt als Schweigen statt als geratene Zahl, und retry_max_wait deckelt auch das Datum.

Stub: --retry-after-date OFF schickt dasselbe als Datum (negativer Wert = Vergangenheit).

Tests: zwei Prüfungen mehr — Datum +2 s wird wie die Zahl 2 gewartet (2,0 s gemessen),
Datum -120 s führt zum sofortigen Versuch (0,2 s, also nur der Backoff).
make test: PASS, 229 Prüfungen, 160 s.
2026-11-08 13:02:37 +00:00

308 lines
14 KiB
C

/* tests/stub.c — OpenAI-compatible stub endpoint for the test suite.
*
* stub <port> <name> [--fail] [--delay SECONDS] [--tls CERT KEY]
* [--fail-n N] [--deny-auth SUBSTR]
*
* --retry-after N puts "Retry-After: N" into every forced 503/429, so a test can check
* that junction waits as long as the provider asked instead of its own backoff.
* --retry-after-date OFF sends the same value as an HTTP date (now + OFF seconds), the
* other form RFC 7231 allows — with a negative OFF it is a date in the past.
* --fail always answers 503 (an endpoint that is up but will not serve)
* --delay waits that long before answering (to exercise "still_working")
* --fail-n answers 503 for the first N requests, then serves — the counter lives in
* $STUB_STATE, so it survives the fork per connection and the test can prove
* that a 5xx is retried on the same endpoint instead of failing over
* --deny-auth answers 429 when the Authorization header contains SUBSTR — the way to
* check that junction rotates to the next key of a pool
*
* The stub echoes what it received in response headers (X-Stub-*) so the tests can
* prove header passthrough and body integrity, including after chunked decoding.
*/
#define _POSIX_C_SOURCE 200809L
#include "../src/conn.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
/* header value of `name` in a request head, or NULL */
static const char *find_header(const char *head, const char *name, char *out, size_t outlen)
{
size_t nlen = strlen(name);
for (const char *p = head; *p; ) {
const char *eol = strstr(p, "\r\n");
if (!eol) break;
if ((size_t)(eol - p) > nlen && !strncasecmp(p, name, nlen) && p[nlen] == ':') {
const char *v = p + nlen + 1;
while (v < eol && (*v == ' ' || *v == '\t')) v++;
size_t vl = (size_t)(eol - v);
if (vl >= outlen) vl = outlen - 1;
memcpy(out, v, vl);
out[vl] = '\0';
return out;
}
p = eol + 2;
}
return NULL;
}
/* Zählt Anfragen über Prozessgrenzen hinweg — der Stub forkt je Verbindung, ein
* Zähler im Speicher des Vaters wäre für das Kind unsichtbar. Die Datei kommt aus
* $STUB_STATE; ohne sie zählt niemand und --fail-n bleibt wirkungslos. */
static int request_serial(void)
{
const char *path = getenv("STUB_STATE");
if (!path || !*path) return 0;
int fd = open(path, O_RDWR | O_CREAT, 0600);
if (fd < 0) return 0;
if (flock(fd, LOCK_EX) != 0) { close(fd); return 0; }
char b[32] = "";
ssize_t got = read(fd, b, sizeof b - 1);
int seen = (got > 0) ? atoi(b) : 0;
seen++;
snprintf(b, sizeof b, "%d\n", seen);
if (lseek(fd, 0, SEEK_SET) == 0 && ftruncate(fd, 0) == 0) {
ssize_t w = write(fd, b, strlen(b));
(void)w;
}
flock(fd, LOCK_UN);
close(fd);
return seen;
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: stub <port> <name> [--fail] [--delay SECONDS] [--fail-n N] [--deny-auth SUBSTR]\n");
return 2;
}
int port = atoi(argv[1]);
const char *name = argv[2];
int fail = 0;
double delay = 0;
int fail_n = 0;
int retry_after = 0;
int retry_after_date = 0;
int has_retry_date = 0;
const char *deny_auth = "";
const char *cert = NULL, *key = NULL;
for (int i = 3; i < argc; i++) {
if (!strcmp(argv[i], "--fail")) fail = 1;
else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]);
else if (!strcmp(argv[i], "--fail-n") && i + 1 < argc) fail_n = atoi(argv[++i]);
else if (!strcmp(argv[i], "--deny-auth") && i + 1 < argc) deny_auth = argv[++i];
else if (!strcmp(argv[i], "--retry-after") && i + 1 < argc) retry_after = atoi(argv[++i]);
else if (!strcmp(argv[i], "--retry-after-date") && i + 1 < argc) {
retry_after_date = atoi(argv[++i]);
has_retry_date = 1;
}
else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; }
}
char tlserr[256];
if (cert && j_tls_server_start(cert, key, tlserr, sizeof tlserr)) {
fprintf(stderr, "stub tls: %s\n", tlserr);
return 1;
}
int lfd = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons((unsigned short)port);
if (bind(lfd, (struct sockaddr *)&addr, sizeof addr) || listen(lfd, 16)) {
perror("bind/listen");
return 1;
}
fprintf(stderr, "stub %s on %d%s\n", name, port, fail ? " (failing)" : "");
signal(SIGCHLD, SIG_IGN); /* one fork per connection, reaped by the kernel */
for (;;) {
int cfd = accept(lfd, NULL, NULL);
if (cfd < 0) continue;
/* A real model server answers several requests at once; a serial stub would
* make the router look serialised when it is not. */
pid_t child = fork();
if (child > 0) { close(cfd); continue; }
if (child < 0) { close(cfd); continue; }
/* Das Kind schließt das Hör-Socket. Sonst hält eine Verbindung, die nie
* fertig wird (Client weg, TLS-Handshake hängt), ein Kind am Leben, und
* mit ihm den Port — der Testlauf ist beendet, :9443 aber weiter belegt,
* und der nächste Lauf verweigert mit "port busy" die Arbeit. */
close(lfd);
j_conn client = J_CONN_INIT;
char aerr[256];
if (cert) {
if (j_tls_server_accept(&client, cfd, aerr, sizeof aerr)) {
fprintf(stderr, "stub tls accept: %s\n", aerr);
close(cfd);
/* Kein Hör-Socket mehr im Kind: jedes `continue` wäre eine
* Endlosschleife um accept() mit EBADF und 100 % CPU. */
_exit(0);
}
} else {
client.fd = cfd;
}
client.role = "stub";
char req[131072];
size_t used = 0;
ssize_t n;
char ioerr[192];
while (used < sizeof req - 1 && (n = j_conn_read(&client, req + used,
sizeof req - 1 - used,
ioerr, sizeof ioerr)) > 0) {
used += (size_t)n;
req[used] = '\0';
if (strstr(req, "\r\n\r\n")) break;
}
if (used == 0) { j_conn_close(&client); _exit(0); }
req[used] = '\0';
/* Zwei künstliche Fehler, ohne die sich Retry und Schlüsselrotation nicht
* nachweisen lassen: ein 503 für die ersten N Anfragen und ein 429 für einen
* bestimmten Schlüssel. */
char authhdr[256] = "";
find_header(req, "Authorization", authhdr, sizeof authhdr);
int forced = 0;
/* Nur Chat-Anfragen zählen: junction holt beim Start GET /v1/models, und diese
* eine Anfrage darf das Fehlerkontingent des Tests nicht verbrauchen. */
int counts = !strncmp(req, "POST", 4) && strstr(req, "/chat/completions");
if (fail_n > 0 && counts && request_serial() <= fail_n) forced = 503;
else if (deny_auth[0] && strstr(authhdr, deny_auth)) forced = 429;
char *head_end = strstr(req, "\r\n\r\n");
size_t head_len = head_end ? (size_t)(head_end + 4 - req) : used;
char cl[32];
long content_length = 0;
if (find_header(req, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10);
while ((long)(used - head_len) < content_length && used < sizeof req - 1) {
n = j_conn_read(&client, req + used, sizeof req - 1 - used, ioerr, sizeof ioerr);
if (n <= 0) break;
used += (size_t)n;
}
req[used] = '\0';
long body_len = (long)used - (long)head_len;
if (body_len < 0) body_len = 0;
if (delay > 0) {
struct timespec ts = { (time_t)delay, (time_t)((delay - (time_t)delay) * 1e9) };
nanosleep(&ts, NULL);
}
char custom[256] = "", static_hdr[256] = "", fwd[256] = "";
/* the model field as it arrived, so the tests can see a rewrite (and a
* rewrite that broke the JSON would show up as a name with junk attached) */
char model[128] = "";
const char *mk = strstr(req, "\"model\"");
if (mk) {
const char *q = strchr(mk, ':');
if (q) {
q++;
while (*q == ' ' || *q == '\t') q++;
if (*q == '"') {
const char *e = strchr(++q, '"');
if (e) {
size_t ml = (size_t)(e - q);
if (ml >= sizeof model) ml = sizeof model - 1;
memcpy(model, q, ml);
model[ml] = '\0';
}
}
}
}
find_header(req, "X-Custom", custom, sizeof custom);
find_header(req, "X-Static", static_hdr, sizeof static_hdr);
find_header(req, "X-Forwarded-For", fwd, sizeof fwd);
char body[1024];
if (forced) {
/* Retry-After: standardmäßig 0 — der Stub weiß nicht, wie lange ein echtes
* Kontingent braucht; die 0 macht klar, dass sofort weiterversucht werden
* darf. Mit --retry-after N sagt er eine Zahl, damit der Test prüfen kann,
* dass junction genau so lange wartet. */
const char *b = (forced == 429) ? "{\"error\":\"rate limited\"}"
: "{\"error\":\"not serving yet\"}";
char ra[64];
if (has_retry_date) {
time_t when = time(NULL) + retry_after_date;
struct tm g;
gmtime_r(&when, &g);
strftime(ra, sizeof ra, "%a, %d %b %Y %H:%M:%S GMT", &g);
} else {
snprintf(ra, sizeof ra, "%d", retry_after);
}
snprintf(body, sizeof body,
"HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nRetry-After: %s\r\n"
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s",
forced, (forced == 429) ? "Too Many Requests" : "Service Unavailable",
ra, strlen(b), b);
} else if (fail) {
const char *b = "{\"error\":\"not serving\"}";
snprintf(body, sizeof body,
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: application/json\r\n"
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b);
} else if (!strncmp(req, "POST", 4) && strstr(req, "/api/show")) {
/* Zweite Quelle für Grenzen: die eigene API eines Endpunkts.
* ollama.com veröffentlicht dort model_info["<arch>.context_length"]. */
const char *show = getenv("STUB_SHOW_CTX");
char b[256];
snprintf(b, sizeof b,
"{\"model_info\":{\"%s.context_length\":%ld},\"details\":{\"family\":\"%s\"}}",
name, show ? strtol(show, NULL, 10) : 0L, name);
snprintf(body, sizeof body,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
"Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b);
} else if (!strncmp(req, "GET", 3)) {
/* Ein Endpunkt, der Grenzen veröffentlicht: nur so lässt sich prüfen, dass
* junction die Modellzahl der Endpunktzahl vorzieht. STUB_CTX/STUB_OUT. */
char b[512];
const char *ectx = getenv("STUB_CTX");
const char *eout = getenv("STUB_OUT");
if (ectx && *ectx)
snprintf(b, sizeof b,
"{\"object\":\"list\",\"data\":[{\"id\":\"%s\",\"limit\":"
"{\"context\":%ld,\"output\":%ld}}]}",
name, strtol(ectx, NULL, 10), eout ? strtol(eout, NULL, 10) : 0L);
else
snprintf(b, sizeof b, "{\"object\":\"list\",\"data\":[{\"id\":\"%s\"}]}", name);
snprintf(body, sizeof body,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
"Content-Length: %zu\r\nX-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n"
"Connection: close\r\n\r\n%s", strlen(b), name, body_len, b);
} else {
char b[512];
snprintf(b, sizeof b,
"{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0,"
"\"message\":{\"role\":\"assistant\",\"content\":\"served by %s\"}}]}",
name, name);
snprintf(body, sizeof body,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
"Content-Length: %zu\r\n"
"X-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n"
"X-Stub-Custom: %s\r\nX-Stub-Static: %s\r\nX-Stub-Xff: %s\r\n"
"X-Stub-Model: %s\r\nX-Stub-Auth: %s\r\n"
"Connection: close\r\n\r\n%s",
strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr, b);
}
if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0)
fprintf(stderr, "stub write failed: %s\n", ioerr);
j_conn_close(&client);
_exit(0);
}
}