commit 137113b0a2a90b2f66023ce73b5a942a9ab7da56 Author: Hermes Agent Date: Thu Oct 29 13:24:31 2026 +0000 junction: pf.conf-style policy router for model endpoints (C99/POSIX) Rules are ordered and first-match-wins: model glob, path glob, required context, hook/retry overrides, pass [,] [as ] or block. Endpoints carry shell pre-hooks (exit != 0 = not yet, retried with backoff after an optional wake command), an offline window after a failed connect, and two timeouts (idle + total) so a thinking model logs still_working instead of looking hung. tests/run.sh: 14 checks against C stubs (failing, gated, slow, dead endpoints). diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09e8ac4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.o +junction +tests/stub +junction.conf diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..65d0307 --- /dev/null +++ b/Makefile @@ -0,0 +1,31 @@ +# junction — C99 + POSIX, no third-party libraries +CC ?= cc +CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Wpedantic -Wshadow -Wconversion +CPPFLAGS += -D_POSIX_C_SOURCE=200809L +LDFLAGS ?= +PREFIX ?= /usr/local + +SRC = src/config.c src/junction.c +OBJ = $(SRC:.c=.o) + +all: junction + +junction: $(OBJ) + $(CC) $(CFLAGS) $(OBJ) -o $@ $(LDFLAGS) + +src/%.o: src/%.c src/config.h + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +test: junction + tests/run.sh + +install: junction + install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/share/junction/hooks + install -m 0755 junction $(DESTDIR)$(PREFIX)/bin/junction + install -m 0755 hooks/*.sh $(DESTDIR)$(PREFIX)/share/junction/hooks/ + install -m 0644 config.example $(DESTDIR)$(PREFIX)/share/junction/junction.conf + +clean: + rm -f $(OBJ) junction + +.PHONY: all test install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..71fc357 --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +# junction + +A policy router for OpenAI-compatible model endpoints. **C99 + POSIX, no +dependencies beyond libc.** + +`junction` sits in front of N model servers and decides **per request** which one +serves it — and what to do when none of them wants to. No product name, no vendor +strings, no branding anywhere in the code: the only name in the sources is +`junction` itself, so branding can be layered on later without touching logic. + +## What it does that a static proxy does not + +- **Ordered rules, like a firewall.** `req ... pass ...` / `block`, first match wins. + Match on model glob, path glob and required context. +- **Shell pre-hooks per endpoint.** A hook that exits non-zero means "not available + yet" — the endpoint is retried with backoff for a bounded time, optionally after + running a wake command. Hooks get the request in their environment. +- **Unreachable means offline, immediately.** A failed TCP connect is not a retry + case: the endpoint is marked offline and skipped in milliseconds. +- **Honest timeouts.** Two of them per endpoint: *idle* ("nothing arrived for N + seconds") and *total*. Silence is logged as `still_working` and the wait + continues; it never looks like a hang and it never abandons a model that is + legitimately thinking. +- **Context-aware.** A request needing more context than an endpoint offers is + refused for that endpoint instead of being silently truncated. +- **Failover with cooldown**, and a `503` that names why each endpoint was skipped. + +## Build / run + +```bash +make # -> ./junction +make test # stub endpoints, no network, no models (~30 s) +sudo make install # /usr/local/bin + /usr/local/share/junction + +./junction --config junction.conf [--port 8090] +curl -s localhost:8090/status | python3 -m json.tool # (only for pretty-printing) +``` + +## Configuration — pf.conf style + +Keyword, arguments, braces. `#` starts a comment, double quotes group words, unknown +keywords are a **hard error with a line number**. Full example: `config.example`. + +``` +listen 0.0.0.0:8090 +chars_per_token 4 +default_max_tokens 4096 +connect_timeout_ms 1500 +offline_hold_s 20 + +endpoint peer1 { + base http://192.0.2.10:8081/v1 + kind remote + context 64000 + priority 20 + timeout 600 + idle_timeout 60 + cooldown 120 + hook /usr/local/share/junction/hooks/check-http.sh +} + +endpoint workstation { + base http://192.0.2.20:8080/v1 + context 128000 + priority 10 + timeout 1800 + idle_timeout 30 + hook_retry 180 # wait up to 3 min for the hooks to pass + hook_backoff 5 + wake /usr/local/share/junction/hooks/wake-wol.sh + hook /usr/local/share/junction/hooks/check-http.sh +} + +endpoint cloud { + base https://api.example.com/v1 + context 200000 + priority 90 + api_key_env EXAMPLE_API_KEY +} + +# rules — first match wins +req need >64000 pass workstation, cloud +req for "*coder*" retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M" +req path "/v1/models" check none pass peer1 +req for "blocked-*" block +req for "*" pass peer1, cloud +``` + +### Rule syntax + +``` +req [for ] [path ] [need >N | ] + ( pass [,...] [as ] | block ) +``` + +- `for` — model name glob (`fnmatch`), matches the model in the request body. +- `need` — estimated tokens (`chars/4 + max_tokens`); `>64000` means "needs more + than 64k", so small endpoints are not even considered. +- `check hooks|none` — override the endpoint's hook list for this rule. +- `retry ` — override `hook_retry` for this rule ("wait up to N s until the box + is ready"). +- `pass a, b` — try `a`, then `b` on failure. +- `as ` — rewrite the `model` field before forwarding (the local box may + serve a different name than the client asked for). +- `block` — refuse with `403`. + +No matching rule at all → `503 no_matching_rule`. That is deliberate: an unmatched +request is a configuration gap, not something to quietly send to a cloud. + +## Endpoint keys + +| key | meaning | +|---|---| +| `base` | OpenAI-compatible base URL including `/v1` (http:// only in this version) | +| `context` | usable context window in tokens | +| `kind` | free-form label (`local`, `remote`, `cloud`) | +| `priority` | lower wins when a rule lists several | +| `timeout` | total wall clock for one request (seconds) | +| `idle_timeout` | silence before `still_working` is logged (seconds) | +| `cooldown` | rest after a failed request (seconds) | +| `hook` | shell command; exit 0 = usable, non-zero = not yet (repeatable) | +| `hook_retry` | how long to keep retrying hooks | +| `hook_backoff` | sleep between hook attempts | +| `wake` | command run once before the hook retries begin | +| `api_key_env` | env var whose value is sent as `Authorization: Bearer ...` | + +## Hooks + +Plain POSIX shell. Environment: + +``` +JUNCTION_BACKEND JUNCTION_BASE JUNCTION_PATH JUNCTION_MODEL +JUNCTION_NEED_TOKENS JUNCTION_ATTEMPT +``` + +Exit non-zero and print the reason on stdout — it lands in `/status` and in the +`503` body. Examples in `hooks/`: `check-http.sh`, `check-budget.sh` +(refuse below a threshold read from any JSON URL), `wake-wol.sh` (magic packet). + +## Control plane + +| Method | Path | Effect | +|---|---|---| +| GET | `/status` | endpoints (state, counters, last error), rules | +| POST | `/admin/pause/` | stop routing there | +| POST | `/admin/resume/` | clear pause + cooldown + offline window | + +Everything else is proxied to the endpoint the rules choose, including streaming +responses (the upstream's framing is relayed byte for byte). + +## Known limits (v0.1, deliberately named) + +- **One request at a time.** The accept loop handles a request to completion before + taking the next one. A slow model therefore queues everything behind it. This + keeps the counters and the state machine honest; a thread pool is the next step. +- **http:// upstreams only.** No TLS client yet — a cloud endpoint needs a local + terminator (stunnel, nginx) in front. +- **Chunked request bodies are not supported** (Content-Length only). Chunked + *responses* are relayed fine. +- **Token estimate is `chars/4`**, good enough to pick an endpoint, not to bill. + +## Tests + +```bash +tests/run.sh +``` + +Builds stubs (C) for: a failing endpoint, a gated one (hook refuses until a file +appears), a slow one (6 s silence), and a dead port. Checks offline detection, +cooldown/failover, hook retry, `still_working` logging, block rules, catch-all, +model rewrite, `no_matching_rule`, and two config-error cases. Pass = `PASS`. diff --git a/config.example b/config.example new file mode 100644 index 0000000..9e125d1 --- /dev/null +++ b/config.example @@ -0,0 +1,77 @@ +# junction.conf — pf.conf-style. keyword, arguments, braces. '#' starts a comment. +# Double quotes group words. Unknown keywords are a hard error with a line number. + +listen 0.0.0.0:8090 +chars_per_token 4 +default_max_tokens 4096 +connect_timeout_ms 1500 +offline_hold_s 20 +max_body_bytes 67108864 + +# --------------------------------------------------------------------- endpoints +endpoint peer1 { + base http://192.0.2.10:8081/v1 + kind remote + context 64000 + priority 20 + timeout 600 + idle_timeout 60 + cooldown 120 + hook /opt/junction/hooks/check-http.sh +} + +endpoint peer2 { + base http://192.0.2.10:8082/v1 + kind remote + context 64000 + priority 20 + timeout 600 + idle_timeout 60 + cooldown 120 + hook /opt/junction/hooks/check-http.sh +} + +endpoint workstation { + base http://192.0.2.20:8080/v1 + kind local + context 128000 + priority 10 + timeout 1800 + idle_timeout 30 + cooldown 60 + hook_retry 180 + hook_backoff 5 + wake /opt/junction/hooks/wake-wol.sh + hook /opt/junction/hooks/check-http.sh + hook /opt/junction/hooks/check-budget.sh +} + +endpoint cloud { + base https://api.example.com/v1 + kind cloud + context 200000 + priority 90 + timeout 900 + idle_timeout 120 + api_key_env EXAMPLE_API_KEY +} + +# ------------------------------------------------------------------------- rules +# First matching rule wins. Rules may use: +# for need >N | +# check hooks|none retry +# pass [,...] [as ] | block + +# Requests that need more context than the peers have go straight to the big box. +req need >64000 pass workstation, cloud + +# Coding work: prefer the workstation, wake it, wait up to 5 minutes for the hooks, +# and hand it the model name it actually serves. +req for "*coder*" check hooks retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M" +req for "Qwen3.8-Flash-Next*" check hooks retry 60 pass workstation, peer1, peer2 + +# Cheap metadata calls never need a model at all. +req path "/v1/models" check none pass peer1, peer2, cloud + +# Anything unseen is refused rather than silently sent to the cloud. +req for "*" block diff --git a/hooks/check-budget.sh b/hooks/check-budget.sh new file mode 100755 index 0000000..2508853 --- /dev/null +++ b/hooks/check-budget.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Example "may I spend energy on this?" hook. +# Reads a JSON document (any URL) and refuses below a threshold. +# JUNCTION_BUDGET_URL e.g. http://127.0.0.1:8123/api/states/sensor.battery +# JUNCTION_BUDGET_FIELD e.g. state +# JUNCTION_BUDGET_MIN e.g. 55 +url="${JUNCTION_BUDGET_URL:-}"; min="${JUNCTION_BUDGET_MIN:-0}" +[ -z "$url" ] && { echo "no_budget_url_configured"; exit 0; } +body=$(curl -s -m 4 "$url" 2>/dev/null) || { echo "budget_source_unreachable"; exit 1; } +value=$(printf '%s' "$body" | python3 -c ' +import json,sys +doc=json.load(sys.stdin) +if isinstance(doc,dict): + print(doc.get("state", doc.get("value",""))) +' 2>/dev/null) +case "$value" in + ''|*[!0-9.]*) echo "budget_unreadable: ${value:-empty}"; exit 1 ;; +esac +if python3 -c "import sys; sys.exit(0 if float('$value') >= float('$min') else 1)"; then + exit 0 +fi +echo "budget_${value}_below_${min}"; exit 1 diff --git a/hooks/check-http.sh b/hooks/check-http.sh new file mode 100755 index 0000000..f8208c7 --- /dev/null +++ b/hooks/check-http.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Usable right now? One short GET against the endpoint's own model list. +# Exit 0 = yes. Anything else = not now, and the reason goes to stdout. +url="${JUNCTION_BASE%/}/models" +code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$url" 2>/dev/null) || { + echo "no_answer_from_${JUNCTION_BACKEND}"; exit 1 +} +case "$code" in + 2*) exit 0 ;; + *) echo "http_${code}_from_${JUNCTION_BACKEND}"; exit 1 ;; +esac diff --git a/hooks/wake-wol.sh b/hooks/wake-wol.sh new file mode 100755 index 0000000..543a47e --- /dev/null +++ b/hooks/wake-wol.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Wake a machine with a magic packet. Needs JUNCTION_WAKE_MAC (aa:bb:cc:dd:ee:ff). +# Uses `wakeonlan` when installed; otherwise sends the packet itself. +[ -z "${JUNCTION_WAKE_MAC:-}" ] && { echo "no_JUNCTION_WAKE_MAC"; exit 1; } +if command -v wakeonlan >/dev/null 2>&1; then + exec wakeonlan "$JUNCTION_WAKE_MAC" +fi +python3 - "$JUNCTION_WAKE_MAC" <<'PY' +import socket, sys +mac = sys.argv[1].replace(":", "").replace("-", "") +if len(mac) != 12: + print("bad_mac"); sys.exit(1) +pkt = b"\xff" * 6 + bytes.fromhex(mac) * 16 +for addr in ("255.255.255.255",): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + s.sendto(pkt, (addr, 9)); s.close() +print("sent") +PY diff --git a/src/config.c b/src/config.c new file mode 100644 index 0000000..9963645 --- /dev/null +++ b/src/config.c @@ -0,0 +1,448 @@ +/* junction/config.c — parser for the pf.conf-style configuration. + * + * The format is deliberately dumb: keyword, arguments, braces. No '=', no nesting + * beyond one level, no quoting rules beyond "double quotes group words". + * + * # global options + * listen 0.0.0.0:8090 + * chars_per_token 4 + * + * endpoint peer1 { + * base http://192.0.2.10:8081/v1 + * context 64000 + * timeout 600 + * hook /opt/junction/hooks/check-http.sh + * } + * + * Unknown keywords are a hard error with a line number. A config typo that silently + * keeps a default is worse than a router that refuses to start. + */ +#define _POSIX_C_SOURCE 200809L + +#include "config.h" + +#include +#include +#include +#include +#include + +#define MAX_WORDS 16 + +static void strip_comment(char *s) +{ + int quoted = 0; + for (char *p = s; *p; p++) { + if (*p == '"') quoted = !quoted; + else if (*p == '#' && !quoted) { *p = '\0'; return; } + } +} + +/* Split into words; double quotes group. Returns word count, -1 on unbalanced quote. + * The words point into `buf`, which is modified in place. */ +static int tokenize(char *buf, char **words, int maxw) +{ + int n = 0; + char *p = buf; + while (*p) { + while (*p && isspace((unsigned char)*p)) p++; + if (!*p) break; + if (n >= maxw) return -2; + if (*p == '"') { + p++; + words[n++] = p; + char *out = p; + int closed = 0; + while (*p) { + if (*p == '"') { closed = 1; p++; break; } + *out++ = *p++; + } + *out = '\0'; + if (!closed) return -1; + } else { + words[n++] = p; + while (*p && !isspace((unsigned char)*p)) p++; + if (*p) *p++ = '\0'; + } + } + return n; +} + +void j_config_defaults(j_config *cfg) +{ + memset(cfg, 0, sizeof *cfg); + snprintf(cfg->listen_host, sizeof cfg->listen_host, "0.0.0.0"); + cfg->listen_port = 8090; + cfg->chars_per_token = 4; + cfg->default_max_tokens = 4096; + cfg->connect_timeout_ms = 1500; + cfg->offline_hold_s = 20; + cfg->max_body_bytes = 64 * 1024 * 1024; + snprintf(cfg->log_prefix, sizeof cfg->log_prefix, "junction"); +} + +static void endpoint_defaults(j_endpoint *ep) +{ + memset(ep, 0, sizeof *ep); + ep->context = 8192; + ep->priority = 50; + ep->timeout_s = 600; + ep->idle_timeout_s = 60; + ep->cooldown_s = 60; + ep->hook_retry_s = 0; + ep->hook_backoff_s = 5; + ep->last_ms = -1; +} + +static int as_double(const char *s, double *dst) +{ + char *end = NULL; + errno = 0; + double d = strtod(s, &end); + if (errno || end == s || (end && *end) || d < 0) return -1; + *dst = d; + return 0; +} + +static int as_long(const char *s, long *dst) +{ + char *end = NULL; + errno = 0; + long n = strtol(s, &end, 10); + if (errno || end == s || (end && *end)) return -1; + *dst = n; + return 0; +} + +static int as_int(const char *s, int *dst) +{ + long n = 0; + if (as_long(s, &n)) return -1; + *dst = (int)n; + return 0; +} + +/* "8090" or "127.0.0.1:8090" or "[::1]:8090" */ +static int parse_listen(j_config *cfg, const char *v) +{ + const char *colon = strrchr(v, ':'); + if (!colon) return as_int(v, &cfg->listen_port); + size_t hlen = (size_t)(colon - v); + if (hlen >= sizeof cfg->listen_host) return -1; + memcpy(cfg->listen_host, v, hlen); + cfg->listen_host[hlen] = '\0'; + if (cfg->listen_host[0] == '[') { /* strip brackets for IPv6 */ + memmove(cfg->listen_host, cfg->listen_host + 1, hlen - 1); + cfg->listen_host[hlen - 2] = '\0'; + } + return as_int(colon + 1, &cfg->listen_port); +} + +static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size_t errlen) +{ + const char *k = w[0]; + if (!strcmp(k, "listen")) { + if (n != 2 || parse_listen(cfg, w[1])) goto bad; + return 0; + } + if (!strcmp(k, "chars_per_token")) { if (n != 2 || as_int(w[1], &cfg->chars_per_token)) goto bad; return 0; } + if (!strcmp(k, "default_max_tokens")) { if (n != 2 || as_long(w[1], &cfg->default_max_tokens)) goto bad; return 0; } + if (!strcmp(k, "connect_timeout_ms")) { if (n != 2 || as_double(w[1], &cfg->connect_timeout_ms)) goto bad; return 0; } + if (!strcmp(k, "offline_hold_s")) { if (n != 2 || as_double(w[1], &cfg->offline_hold_s)) goto bad; return 0; } + if (!strcmp(k, "max_body_bytes")) { if (n != 2 || as_int(w[1], &cfg->max_body_bytes)) goto bad; return 0; } + if (!strcmp(k, "log_prefix")) { + if (n != 2) goto bad; + snprintf(cfg->log_prefix, sizeof cfg->log_prefix, "%s", w[1]); + return 0; + } + snprintf(err, errlen, "line %d: unknown keyword '%s'", lineno, k); + return -1; +bad: + snprintf(err, errlen, "line %d: bad arguments for '%s'", lineno, k); + return -1; +} + +static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, size_t errlen) +{ + const char *k = w[0]; + if (!strcmp(k, "base")) { if (n != 2) goto bad; snprintf(ep->base, sizeof ep->base, "%s", w[1]); return 0; } + if (!strcmp(k, "kind")) { if (n != 2) goto bad; snprintf(ep->kind, sizeof ep->kind, "%s", w[1]); return 0; } + if (!strcmp(k, "context")) { if (n != 2 || as_long(w[1], &ep->context)) goto bad; return 0; } + if (!strcmp(k, "priority")) { if (n != 2 || as_int(w[1], &ep->priority)) goto bad; return 0; } + if (!strcmp(k, "timeout")) { if (n != 2 || as_double(w[1], &ep->timeout_s)) goto bad; return 0; } + if (!strcmp(k, "idle_timeout")) { if (n != 2 || as_double(w[1], &ep->idle_timeout_s)) goto bad; return 0; } + if (!strcmp(k, "cooldown")) { if (n != 2 || as_double(w[1], &ep->cooldown_s)) goto bad; return 0; } + if (!strcmp(k, "hook_retry")) { if (n != 2 || as_double(w[1], &ep->hook_retry_s)) goto bad; return 0; } + if (!strcmp(k, "hook_backoff")) { if (n != 2 || as_double(w[1], &ep->hook_backoff_s)) goto bad; return 0; } + if (!strcmp(k, "wake")) { if (n != 2) goto bad; snprintf(ep->wake, sizeof ep->wake, "%s", w[1]); return 0; } + if (!strcmp(k, "api_key_env")) { if (n != 2) goto bad; snprintf(ep->api_key_env, sizeof ep->api_key_env, "%s", w[1]); return 0; } + if (!strcmp(k, "hook")) { + if (n < 2) goto bad; + if (ep->hook_count >= J_MAX_HOOKS) { + snprintf(err, errlen, "line %d: endpoint %s has more than %d hooks", lineno, ep->name, J_MAX_HOOKS); + return -1; + } + /* join remaining words so an unquoted command with arguments works */ + char joined[J_CMD_MAX] = ""; + size_t used = 0; + for (int i = 1; i < n && used < sizeof joined - 1; i++) { + int wrote = snprintf(joined + used, sizeof joined - used, "%s%s", + i > 1 ? " " : "", w[i]); + if (wrote < 0) break; + used += (size_t)wrote; + } + snprintf(ep->hooks[ep->hook_count++], J_CMD_MAX, "%s", joined); + return 0; + } + snprintf(err, errlen, "line %d: unknown endpoint keyword '%s'", lineno, k); + return -1; +bad: + snprintf(err, errlen, "line %d: bad arguments for '%s'", lineno, k); + return -1; +} + + +/* --- rules: req [for GLOB] [path GLOB] [need OP N] [check hooks|none] + * [retry SECONDS] (pass EP[,EP...] [as MODEL] | block) */ +static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t errlen) +{ + memset(r, 0, sizeof *r); + r->need_min = -1; + r->need_max = -1; + r->check = J_CHECK_INHERIT; + r->retry_s = -1; + r->line = lineno; + + int i = 1; /* w[0] == "req" */ + while (i < n) { + const char *k = w[i]; + if (!strcmp(k, "for")) { + if (i + 1 >= n) goto bad; + snprintf(r->model_glob, sizeof r->model_glob, "%s", w[i + 1]); + i += 2; + } else if (!strcmp(k, "path")) { + if (i + 1 >= n) goto bad; + snprintf(r->path_glob, sizeof r->path_glob, "%s", w[i + 1]); + i += 2; + } else if (!strcmp(k, "need")) { + if (i + 1 >= n) goto bad; + const char *v = w[i + 1]; + long num = 0; + if (v[0] == '>') { if (as_long(v + (v[1] == '=' ? 2 : 1), &num)) goto bad; + r->need_min = v[1] == '=' ? num : num + 1; } + else if (v[0] == '<') { if (as_long(v + (v[1] == '=' ? 2 : 1), &num)) goto bad; + r->need_max = v[1] == '=' ? num : num - 1; } + else { if (as_long(v, &num)) goto bad; r->need_min = r->need_max = num; } + i += 2; + } else if (!strcmp(k, "check")) { + if (i + 1 >= n) goto bad; + if (!strcmp(w[i + 1], "hooks")) r->check = J_CHECK_HOOKS; + else if (!strcmp(w[i + 1], "none")) r->check = J_CHECK_NONE; + else goto bad; + i += 2; + } else if (!strcmp(k, "retry")) { + if (i + 1 >= n || as_double(w[i + 1], &r->retry_s)) goto bad; + i += 2; + } else if (!strcmp(k, "block")) { + r->block = 1; + i++; + return 0; + } else if (!strcmp(k, "pass")) { + if (i + 1 >= n) goto bad; + /* targets run until "as" or the end of the line; they may be written as + * one comma list, as separate words, or both. */ + int j = i + 1; + char joined[J_CMD_MAX] = ""; + size_t ju = 0; + for (; j < n && strcmp(w[j], "as"); j++) { + int wrote = snprintf(joined + ju, sizeof joined - ju, "%s%s", + ju ? "," : "", w[j]); + if (wrote < 0) break; + ju += (size_t)wrote; + } + char *save = NULL; + for (char *tok = strtok_r(joined, ",", &save); tok; + tok = strtok_r(NULL, ",", &save)) { + while (*tok == ' ') tok++; + if (!*tok) continue; + if (r->target_count >= J_MAX_TARGETS) { + snprintf(err, errlen, "line %d: more than %d pass targets", lineno, J_MAX_TARGETS); + return -1; + } + snprintf(r->targets[r->target_count++], J_NAME_MAX, "%s", tok); + } + if (!r->target_count) goto bad; + i = j; + /* optional: as MODEL */ + if (i < n && !strcmp(w[i], "as")) { + if (i + 1 >= n) goto bad; + snprintf(r->rewrite_model, sizeof r->rewrite_model, "%s", w[i + 1]); + i += 2; + } + if (i != n) goto bad; + return 0; + } else { + snprintf(err, errlen, "line %d: unknown rule keyword '%s'", lineno, k); + return -1; + } + } + snprintf(err, errlen, "line %d: rule without 'pass' or 'block'", lineno); + return -1; +bad: + snprintf(err, errlen, "line %d: bad arguments in rule", lineno); + return -1; +} + +int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen) +{ + FILE *fh = fopen(path, "r"); + if (!fh) { + snprintf(err, errlen, "cannot open %s: %s", path, strerror(errno)); + return -1; + } + j_config_defaults(cfg); + + char line[4096]; + int lineno = 0; + j_endpoint *cur = NULL; + + while (fgets(line, sizeof line, fh)) { + lineno++; + strip_comment(line); + char *w[MAX_WORDS]; + int n = tokenize(line, w, MAX_WORDS); + if (n == 0) continue; + if (n < 0) { + snprintf(err, errlen, "line %d: unbalanced quote", lineno); + fclose(fh); + return -1; + } + + if (!strcmp(w[0], "}")) { + if (!cur) { + snprintf(err, errlen, "line %d: '}' without an open block", lineno); + fclose(fh); + return -1; + } + cur = NULL; + continue; + } + + if (!strcmp(w[0], "req")) { + if (cur) { + snprintf(err, errlen, "line %d: rules are not allowed inside an endpoint block", lineno); + fclose(fh); + return -1; + } + if (cfg->rule_count >= J_MAX_RULES) { + snprintf(err, errlen, "more than %d rules", J_MAX_RULES); + fclose(fh); + return -1; + } + if (parse_rule(w, n, lineno, &cfg->rules[cfg->rule_count], err, errlen)) { + fclose(fh); + return -1; + } + cfg->rule_count++; + continue; + } + + if (!strcmp(w[0], "pass") || !strcmp(w[0], "block")) { + /* bare catch-all rule: pass a, b / block */ + char **shifted = w; + (void)shifted; + if (cur) { + snprintf(err, errlen, "line %d: rules are not allowed inside an endpoint block", lineno); + fclose(fh); + return -1; + } + if (cfg->rule_count >= J_MAX_RULES) { + snprintf(err, errlen, "more than %d rules", J_MAX_RULES); + fclose(fh); + return -1; + } + /* synthesise "req " */ + char synth[4096] = "req"; + for (int i = 0; i < n; i++) { + size_t used = strlen(synth); + snprintf(synth + used, sizeof synth - used, " %s", w[i]); + } + char *w2[MAX_WORDS]; + int n2 = tokenize(synth, w2, MAX_WORDS); + if (n2 < 2 || parse_rule(w2, n2, lineno, &cfg->rules[cfg->rule_count], err, errlen)) { + if (!err[0]) + snprintf(err, errlen, "line %d: rule without 'req' malformed", lineno); + fclose(fh); + return -1; + } + cfg->rule_count++; + continue; + } + + if (!strcmp(w[0], "endpoint") || !strcmp(w[0], "backend")) { + /* endpoint NAME { — the brace must be the last word */ + if (n != 3 || strcmp(w[2], "{")) { + snprintf(err, errlen, "line %d: expected 'endpoint NAME {'", lineno); + fclose(fh); + return -1; + } + if (cur) { + snprintf(err, errlen, "line %d: nested endpoint block", lineno); + fclose(fh); + return -1; + } + if (cfg->endpoint_count >= J_MAX_ENDPOINTS) { + snprintf(err, errlen, "more than %d endpoints", J_MAX_ENDPOINTS); + fclose(fh); + return -1; + } + cur = &cfg->endpoints[cfg->endpoint_count++]; + endpoint_defaults(cur); + snprintf(cur->name, sizeof cur->name, "%s", w[1]); + continue; + } + + int rc = cur ? endpoint_kw(cur, w, n, lineno, err, errlen) + : global_kw(cfg, w, n, lineno, err, errlen); + if (rc) { + fclose(fh); + return -1; + } + } + fclose(fh); + + if (cur) { + snprintf(err, errlen, "endpoint %s: block not closed with '}'", cur->name); + return -1; + } + if (!cfg->endpoint_count) { + snprintf(err, errlen, "no 'endpoint NAME {' blocks in %s", path); + return -1; + } + for (int i = 0; i < cfg->endpoint_count; i++) { + j_endpoint *ep = &cfg->endpoints[i]; + if (!ep->base[0]) { + snprintf(err, errlen, "endpoint %s: 'base' is required", ep->name); + return -1; + } + if (strncmp(ep->base, "http://", 7) && strncmp(ep->base, "https://", 8)) { + snprintf(err, errlen, "endpoint %s: base must start with http:// or https://", ep->name); + return -1; + } + if (!ep->kind[0]) snprintf(ep->kind, sizeof ep->kind, "remote"); + } + for (int i = 0; i < cfg->rule_count; i++) { + j_rule *r = &cfg->rules[i]; + for (int t = 0; t < r->target_count; t++) { + int found = 0; + for (int e = 0; e < cfg->endpoint_count; e++) + if (!strcmp(cfg->endpoints[e].name, r->targets[t])) { found = 1; break; } + if (!found) { + snprintf(err, errlen, "line %d: rule passes to unknown endpoint '%s'", + r->line, r->targets[t]); + return -1; + } + } + } + return 0; +} diff --git a/src/config.h b/src/config.h new file mode 100644 index 0000000..e32a1b8 --- /dev/null +++ b/src/config.h @@ -0,0 +1,116 @@ +/* junction/config.h — configuration types for the pf.conf-style file. + * + * Grammar (one directive per line, '#' starts a comment, double quotes group words): + * + * listen 0.0.0.0:8090 + * chars_per_token 4 + * default_max_tokens 4096 + * connect_timeout_ms 1500 + * offline_hold_s 20 + * max_body_bytes 67108864 + * log_prefix junction + * + * endpoint peer1 { + * base http://192.0.2.10:8081/v1 + * kind remote + * context 64000 + * priority 20 + * timeout 600 + * idle_timeout 60 + * cooldown 120 + * hook /opt/junction/hooks/check-http.sh + * hook_retry 180 + * hook_backoff 5 + * wake /opt/junction/hooks/wake-wol.sh + * api_key_env SOME_KEY + * } + * + * # rules: first match wins, like a firewall's ordered rules + * req for "Qwen3.8*" need >64000 pass cloud + * req for "*coder*" check hooks retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M" + * req path "/v1/models" pass peer1, peer2 + * pass peer1, peer2, cloud # catch-all + * req for "blocked-*" block + */ +#ifndef JUNCTION_CONFIG_H +#define JUNCTION_CONFIG_H + +#include + +#define J_MAX_ENDPOINTS 32 +#define J_MAX_HOOKS 8 +#define J_MAX_RULES 64 +#define J_MAX_TARGETS 4 +#define J_NAME_MAX 64 +#define J_URL_MAX 512 +#define J_CMD_MAX 512 +#define J_GLOB_MAX 128 + +typedef struct { + char name[J_NAME_MAX]; + char base[J_URL_MAX]; + char kind[J_NAME_MAX]; + + long context; + int priority; + double timeout_s; + double idle_timeout_s; + double cooldown_s; + double hook_retry_s; + double hook_backoff_s; + + char hooks[J_MAX_HOOKS][J_CMD_MAX]; + int hook_count; + char wake[J_CMD_MAX]; + char api_key_env[J_NAME_MAX]; + + /* runtime state — not from the file */ + double offline_until; + double cooldown_until; + int paused; + int inflight; + unsigned long ok_count; + unsigned long fail_count; + long last_ms; + char last_error[256]; + char last_hook_reason[256]; +} j_endpoint; + +enum { J_CHECK_INHERIT = -1, J_CHECK_NONE = 0, J_CHECK_HOOKS = 1 }; + +typedef struct { + char model_glob[J_GLOB_MAX]; /* "" = any */ + char path_glob[J_GLOB_MAX]; /* "" = any */ + long need_min; /* -1 = unset */ + long need_max; /* -1 = unset */ + int check; /* J_CHECK_* */ + double retry_s; /* <0 = inherit from endpoint */ + + int block; /* 1 = refuse the request */ + char targets[J_MAX_TARGETS][J_NAME_MAX]; + int target_count; + char rewrite_model[J_GLOB_MAX];/* "" = pass the model through unchanged */ + int line; +} j_rule; + +typedef struct { + char listen_host[J_NAME_MAX]; + int listen_port; + int chars_per_token; + long default_max_tokens; + double connect_timeout_ms; + double offline_hold_s; + int max_body_bytes; + char log_prefix[J_NAME_MAX]; + + j_endpoint endpoints[J_MAX_ENDPOINTS]; + int endpoint_count; + + j_rule rules[J_MAX_RULES]; + int rule_count; +} j_config; + +void j_config_defaults(j_config *cfg); +int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen); + +#endif /* JUNCTION_CONFIG_H */ diff --git a/src/junction.c b/src/junction.c new file mode 100644 index 0000000..e042ab9 --- /dev/null +++ b/src/junction.c @@ -0,0 +1,843 @@ +/* junction/junction.c — HTTP surface, rule routing, hooks, forwarding. + * + * C99 + POSIX, no third-party libraries. One request at a time on purpose (README, + * "Known limits"). + */ +#define _POSIX_C_SOURCE 200809L + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define HDR_MAX 32768 +#define RELAY_CHUNK 8192 + +static j_config CFG; + +/* ------------------------------------------------------------------ utility */ +static double now_s(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +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); + fprintf(stderr, "[%s] %s%s%s\n", CFG.log_prefix, event, n > 0 ? " " : "", n > 0 ? line : ""); + fflush(stderr); +} + +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 size_t count_value_chars(const char *body, const char *key) +{ + char pat[64]; + snprintf(pat, sizeof pat, "\"%s\"", key); + size_t total = 0; + for (const char *p = body; (p = strstr(p, pat)) != NULL; ) { + p += strlen(pat); + while (*p && *p != ':') p++; + if (*p == ':') p++; + while (*p && isspace((unsigned char)*p)) p++; + if (*p != '"') continue; + p++; + while (*p) { + if (*p == '\\' && p[1]) { p += 2; total++; continue; } + if (*p == '"') break; + p++; total++; + } + } + return total; +} + +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 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 = strstr(body, pat); + 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'; +} + +static long need_tokens(const char *body) +{ + size_t chars = 0; + if (body) { + chars += count_value_chars(body, "content"); + chars += count_value_chars(body, "prompt"); + } + long mt = body ? json_int_value(body, "max_tokens") : -1; + if (mt < 0 && body) mt = json_int_value(body, "max_completion_tokens"); + if (mt < 0) mt = CFG.default_max_tokens; + long cpt = CFG.chars_per_token > 0 ? CFG.chars_per_token : 4; + return (long)(chars / (size_t)cpt) + mt; +} + +/* ------------------------------------------------------------------- request */ +typedef struct { + char method[16]; + char path[2048]; + char *headers; + char *body; + size_t body_len; +} j_request; + +/* Returns the length of the header block (including its terminating CRLFCRLF), or -1/-2. + * `extra` receives the number of bytes read PAST that block — a single read() almost + * always returns body bytes too, and losing that count makes the caller wait forever + * for a body that already arrived. */ +static ssize_t read_header_block(int fd, char *buf, size_t cap, double idle_s, double deadline, + const char *who, size_t *extra) +{ + if (extra) *extra = 0; + size_t used = 0; + for (;;) { + if (now_s() >= deadline) return -2; + struct pollfd p = { .fd = fd, .events = POLLIN, .revents = 0 }; + double left = deadline - now_s(); + double t = left < idle_s ? left : idle_s; + int pr = poll(&p, 1, (int)(t * 1000.0) + 1); + if (pr == 0) { jlog("still_working", "side=%s silent_s=%.1f", who, idle_s); continue; } + if (pr < 0) { if (errno == EINTR) continue; return -1; } + if (used >= cap - 1) return -1; + ssize_t n = read(fd, buf + used, cap - 1 - used); + if (n < 0) { if (errno == EINTR) continue; return -1; } + if (n == 0) return -1; + used += (size_t)n; + buf[used] = '\0'; + char *end = strstr(buf, "\r\n\r\n"); + if (end) { + size_t hlen = (size_t)(end + 4 - buf); + if (extra) *extra = used - hlen; + return (ssize_t)hlen; + } + } +} + +static int read_exact(int fd, char *buf, size_t len, double idle_s, double deadline, const char *who) +{ + size_t got = 0; + while (got < len) { + if (now_s() >= deadline) return -1; + struct pollfd p = { .fd = fd, .events = POLLIN, .revents = 0 }; + double left = deadline - now_s(); + double t = left < idle_s ? left : idle_s; + int pr = poll(&p, 1, (int)(t * 1000.0) + 1); + if (pr == 0) { jlog("still_working", "side=%s silent_s=%.1f", who, idle_s); continue; } + if (pr < 0) { if (errno == EINTR) continue; return -1; } + ssize_t n = read(fd, buf + got, len - got); + if (n <= 0) { if (n < 0 && errno == EINTR) continue; return -1; } + got += (size_t)n; + } + return 0; +} + +static int header_value(const char *headers, const char *name, char *out, size_t outlen) +{ + size_t nlen = strlen(name); + for (const char *p = headers; *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 0; + } + p = eol + 2; + } + return -1; +} + +static int has_header_token(const char *headers, const char *name, const char *token) +{ + char v[512]; + if (header_value(headers, name, v, sizeof v)) return 0; + for (char *p = v; *p; p++) *p = (char)tolower((unsigned char)*p); + return strstr(v, token) != NULL; +} + +/* ------------------------------------------------------------------- network */ +static int split_url(const char *base, char *host, size_t hostlen, char *port, size_t portlen, + char *prefix, size_t prefixlen) +{ + const char *p = base; + if (!strncmp(p, "https://", 8)) 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", base[4] == 's' ? "443" : "80"); + } + snprintf(prefix, prefixlen, "%s", slash ? slash : ""); + size_t pl2 = strlen(prefix); + while (pl2 > 1 && prefix[pl2 - 1] == '/') prefix[--pl2] = '\0'; + return 0; +} + +static int tcp_connect(const char *host, const char *port, double timeout_ms) +{ + struct addrinfo hints, *res = NULL; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo(host, port, &hints, &res) != 0) return -1; + + int fd = -1; + for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { + int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); + if (s < 0) continue; + int flags = fcntl(s, F_GETFL, 0); + fcntl(s, F_SETFL, flags | O_NONBLOCK); + int rc = connect(s, ai->ai_addr, ai->ai_addrlen); + if (rc == 0) { fcntl(s, F_SETFL, flags); fd = s; break; } + if (errno == EINPROGRESS) { + struct pollfd p = { .fd = s, .events = POLLOUT, .revents = 0 }; + if (poll(&p, 1, (int)timeout_ms) == 1) { + int err = 0; + socklen_t el = sizeof err; + getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &el); + if (!err) { fcntl(s, F_SETFL, flags); fd = s; break; } + } + } + close(s); + } + freeaddrinfo(res); + return fd; +} + +static int endpoint_reachable(const j_endpoint *ep) +{ + char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; + if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix)) + return 0; + int fd = tcp_connect(host, port, CFG.connect_timeout_ms); + if (fd < 0) return 0; + close(fd); + return 1; +} + +/* --------------------------------------------------------------------- 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'; + } + } + pid_t w = waitpid(pid, &status, WNOHANG); + if (w == 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; +} + +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 (;;) { + if (!endpoint_reachable(ep)) return -2; + 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)) { + snprintf(ep->last_hook_reason, sizeof ep->last_hook_reason, "%s", reason); + 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++; + } +} + +/* ------------------------------------------------------------------ respond */ +static void send_simple(int fd, int code, const char *reason, const char *body) +{ + char hdr[256]; + int n = snprintf(hdr, sizeof hdr, + "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\n" + "Content-Length: %zu\r\nConnection: close\r\n\r\n", + code, reason, strlen(body)); + if (write(fd, hdr, (size_t)n) < 0) return; + if (write(fd, body, strlen(body)) < 0) return; +} + +static void status_page(int fd) +{ + size_t cap = 4096 + (size_t)CFG.endpoint_count * 1200 + (size_t)CFG.rule_count * 200; + char *out = calloc(1, cap); + if (!out) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } + double t = now_s(); + size_t used = (size_t)snprintf(out, cap, "{\"endpoints\":["); + for (int i = 0; i < CFG.endpoint_count; i++) { + j_endpoint *ep = &CFG.endpoints[i]; + char err[512], hook[512]; + json_escape(ep->last_error, err, sizeof err); + 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,\"offline_s\":%d,\"cooldown_s\":%d,\"hooks\":%d," + "\"wakeable\":%s,\"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, + (int)(ep->offline_until > t ? ep->offline_until - t : 0), + (int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0), + ep->hook_count, ep->wake[0] ? "true" : "false", err, hook); + } + used += (size_t)snprintf(out + used, cap - used, "],\"rules\":["); + for (int i = 0; i < CFG.rule_count; i++) { + j_rule *r = &CFG.rules[i]; + used += (size_t)snprintf(out + used, cap - used, + "%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"targets\":\"%s\"}", + i ? "," : "", r->line, r->model_glob, r->path_glob, + r->block ? "true" : "false", r->targets[0]); + } + snprintf(out + used, cap - used, "]}"); + send_simple(fd, 200, "OK", out); + free(out); +} + +/* --------------------------------------------------------------------- rules */ +static int rule_matches(const j_rule *r, const char *path, const char *model, long need) +{ + 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; + return 1; +} + +static j_rule *first_matching_rule(const char *path, const char *model, long need) +{ + for (int i = 0; i < CFG.rule_count; i++) + if (rule_matches(&CFG.rules[i], path, model, need)) return &CFG.rules[i]; + return NULL; +} + +/* Rewrite the "model" value inside the JSON body. Returns a new buffer or 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); + size_t post = strlen(end + 1); + 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 + 1, post + 1); + return out; +} + +/* ----------------------------------------------------------------- forwarding */ +/* Raw relay of (already framed) upstream bytes: chunked framing and streaming pass + * through untouched, so we cannot corrupt a stream by re-chunking it. */ +static int relay_body(int out_fd, int in_fd, long content_length, double idle_s, + double deadline, int *progress_at) +{ + static char buf[RELAY_CHUNK]; + long remaining = content_length; + for (;;) { + if (now_s() >= deadline) return -1; + struct pollfd p = { .fd = in_fd, .events = POLLIN, .revents = 0 }; + double left = deadline - now_s(); + double t = left < idle_s ? left : idle_s; + int pr = poll(&p, 1, (int)(t * 1000.0) + 1); + if (pr == 0) { *progress_at = 1; jlog("still_working", "side=upstream silent_s=%.1f", idle_s); continue; } + if (pr < 0) { if (errno == EINTR) continue; return -1; } + size_t want = sizeof buf; + if (remaining >= 0 && (long)want > remaining) want = (size_t)remaining; + ssize_t n = read(in_fd, buf, want); + if (n < 0) { if (errno == EINTR) continue; return -1; } + if (n == 0) return (remaining > 0) ? -1 : 0; + if (write(out_fd, buf, (size_t)n) != n) return -1; + if (remaining > 0) { + remaining -= n; + if (remaining == 0) return 0; + } + *progress_at = 1; + } +} + +static int forward(int client_fd, j_endpoint *ep, const char *method, const char *path, + const char *client_headers, const char *body, size_t body_len, long need) +{ + (void)need; + char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; + if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix)) + return -1; + + int fd = tcp_connect(host, port, CFG.connect_timeout_ms); + if (fd < 0) return -1; + + /* build the upstream request: client headers minus hop-by-hop, plus Host */ + char target[4096]; + if (!strncmp(path, "/v1", 3)) snprintf(target, sizeof target, "%s%s", prefix, path + 3); + else snprintf(target, sizeof target, "%s%s", prefix, path); + + char req[HDR_MAX]; + size_t used = (size_t)snprintf(req, sizeof req, "%s %s HTTP/1.1\r\n", method, target); + for (const char *p = client_headers; *p && used < sizeof req - 64; ) { + const char *eol = strstr(p, "\r\n"); + if (!eol) break; + size_t len = (size_t)(eol - p); + if (len > 0 && strncasecmp(p, "Host:", 5) && strncasecmp(p, "Connection:", 11) && + strncasecmp(p, "Content-Length:", 15) && strncasecmp(p, "Transfer-Encoding:", 18)) { + memcpy(req + used, p, len); + used += len; + memcpy(req + used, "\r\n", 2); + used += 2; + } + p = eol + 2; + } + used += (size_t)snprintf(req + used, sizeof req - used, "Host: %s\r\n", host); + if (ep->api_key_env[0]) { + const char *key = getenv(ep->api_key_env); + if (key) used += (size_t)snprintf(req + used, sizeof req - used, + "Authorization: Bearer %s\r\n", key); + } + if (body) used += (size_t)snprintf(req + used, sizeof req - used, + "Content-Length: %zu\r\n", body_len); + used += (size_t)snprintf(req + used, sizeof req - used, "Connection: close\r\n\r\n"); + + double deadline = now_s() + ep->timeout_s; + if (write(fd, req, used) != (ssize_t)used) { close(fd); return -1; } + if (body && body_len && write(fd, body, body_len) != (ssize_t)body_len) { close(fd); return -1; } + + char *hdr = malloc(HDR_MAX); + if (!hdr) { close(fd); return -1; } + size_t up_extra = 0; + ssize_t hlen = read_header_block(fd, hdr, HDR_MAX, ep->idle_timeout_s, deadline, "upstream", + &up_extra); + if (hlen <= 0) { free(hdr); close(fd); ep->last_error[0] ? 0 : snprintf(ep->last_error, sizeof ep->last_error, "no_response_headers"); return -1; } + + int status = 0; + if (sscanf(hdr, "HTTP/%*d.%*d %d", &status) != 1) { + free(hdr); close(fd); + snprintf(ep->last_error, sizeof ep->last_error, "unparsable_status_line"); + return -1; + } + /* A 5xx or 429 is the endpoint failing, not an answer: fail over instead of + * passing a broken reply to the caller. */ + if (status >= 500 || status == 429) { + snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", status); + free(hdr); close(fd); + return -2; + } + + char cl[64]; + long content_length = -1; + if (!header_value(hdr, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); + int is_chunked = has_header_token(hdr, "Transfer-Encoding", "chunked"); + + /* relay the header block minus its terminator, so the client sees the upstream's + * framing (chunked stays chunked, content-length stays content-length) */ + char *hdr_end = strstr(hdr, "\r\n\r\n"); + if (hdr_end) { + if (write(client_fd, hdr, (size_t)(hdr_end - hdr)) < 0) { free(hdr); close(fd); return -1; } + if (write(client_fd, "\r\n\r\n", 4) < 0) { free(hdr); close(fd); return -1; } + } + /* Body bytes that arrived together with the headers are already in hand: + * write them first or the client waits for bytes we have already consumed. */ + size_t buffered = up_extra; + if (content_length >= 0 && buffered > (size_t)content_length) buffered = (size_t)content_length; + if (buffered && write(client_fd, hdr + hlen, buffered) != (ssize_t)buffered) { + free(hdr); close(fd); return -1; + } + free(hdr); + + int progress = 0; + int rc; + if (is_chunked || content_length < 0) { + /* chunked or connection-close framing: the upstream's own framing is relayed + * byte for byte, so EOF (or the chunk terminator) ends it. */ + (void)relay_body(client_fd, fd, -1, ep->idle_timeout_s, deadline, &progress); + rc = 0; + } else { + long remaining = content_length - (long)buffered; + rc = remaining > 0 ? relay_body(client_fd, fd, remaining, ep->idle_timeout_s, + deadline, &progress) : 0; + } + close(fd); + return rc == 0 ? 0 : -1; +} + +/* --------------------------------------------------------------- connection */ +static void admin(int fd, const char *path) +{ + const char *p = path + strlen("/admin/"); + char action[16], name[J_NAME_MAX]; + const char *slash = strchr(p, '/'); + if (!slash) { send_simple(fd, 400, "Bad Request", "{\"error\":\"use /admin/pause|resume/\"}"); return; } + snprintf(action, sizeof action, "%.*s", (int)(slash - p), p); + snprintf(name, sizeof name, "%s", slash + 1); + + 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(fd, 400, "Bad Request", "{\"error\":\"use pause or resume\"}"); return; } + jlog("admin", "endpoint=%s action=%s paused=%d", name, action, ep->paused); + char body[128]; + snprintf(body, sizeof body, "{\"name\":\"%s\",\"paused\":%s}", name, ep->paused ? "true" : "false"); + send_simple(fd, 200, "OK", body); + return; + } + send_simple(fd, 404, "Not Found", "{\"error\":\"unknown endpoint\"}"); +} + +static void handle_client(int fd) +{ + char *hdr = malloc(HDR_MAX); + if (!hdr) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } + double deadline = now_s() + 120.0; + size_t extra = 0; + ssize_t hlen = read_header_block(fd, hdr, HDR_MAX, 60.0, deadline, "client", &extra); + if (hlen <= 0) { free(hdr); return; } + /* NOTE: do NOT write hdr[hlen] = '\0'. read_header_block already terminated the + * buffer at the END of everything it read, and the body bytes that came with the + * headers live right after the header block — terminating at hlen overwrote the + * first body byte with NUL, so the body looked empty while body_len said 84. */ + + j_request rq; + memset(&rq, 0, sizeof rq); + if (sscanf(hdr, "%15s %2047s", rq.method, rq.path) != 2) { + send_simple(fd, 400, "Bad Request", "{\"error\":\"bad request line\"}"); + free(hdr); + return; + } + rq.headers = strstr(hdr, "\r\n") + 2; + + char cl[64]; + long content_length = 0; + if (!header_value(rq.headers, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); + if (content_length < 0) content_length = 0; + if (content_length > CFG.max_body_bytes) { + send_simple(fd, 413, "Payload Too Large", "{\"error\":\"body_too_large\"}"); + free(hdr); + return; + } + + char *head_end = strstr(hdr, "\r\n\r\n") + 4; + if (content_length) { + rq.body = calloc((size_t)content_length + 1, 1); + if (!rq.body) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); free(hdr); return; } + size_t copied = extra < (size_t)content_length ? extra : (size_t)content_length; + memcpy(rq.body, head_end, copied); + if (copied < (size_t)content_length) { + if (read_exact(fd, rq.body + copied, (size_t)content_length - copied, 30.0, + now_s() + 120.0, "client")) { + send_simple(fd, 400, "Bad Request", "{\"error\":\"body_incomplete\"}"); + free(rq.body); free(hdr); + return; + } + } + rq.body_len = (size_t)content_length; + } + + /* control plane */ + if (!strcmp(rq.path, "/status")) { status_page(fd); free(rq.body); free(hdr); return; } + if (!strncmp(rq.path, "/admin/", 7)) { admin(fd, rq.path); free(rq.body); free(hdr); return; } + + long need = need_tokens(rq.body); + char model[J_GLOB_MAX]; + json_str_value(rq.body ? rq.body : "", "model", model, sizeof model); + + j_rule *rule = first_matching_rule(rq.path, model, need); + 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}", + epath, emodel, need); + send_simple(fd, 503, "Service Unavailable", body); + free(rq.body); free(hdr); + return; + } + 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(fd, 403, "Forbidden", body); + free(rq.body); free(hdr); + return; + } + + const char *out_body = rq.body; + char *rewritten = NULL; + const char *out_model = model; + if (rule->rewrite_model[0] && rq.body) { + rewritten = rewrite_model(rq.body, rule->rewrite_model); + if (rewritten) { out_body = rewritten; out_model = rule->rewrite_model; } + } + size_t out_len = out_body ? strlen(out_body) : 0; + + char attempts[768] = ""; + for (int t = 0; t < rule->target_count; t++) { + 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; + + if (ep->paused) { strncat(attempts, " paused", sizeof attempts - strlen(attempts) - 1); continue; } + if (ep->cooldown_until > now_s()) { strncat(attempts, " cooling", sizeof attempts - strlen(attempts) - 1); continue; } + if (ep->context < need) { strncat(attempts, " context", sizeof attempts - strlen(attempts) - 1); continue; } + if (ep->offline_until > now_s()) { strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1); continue; } + + if (!endpoint_reachable(ep)) { + ep->offline_until = now_s() + CFG.offline_hold_s; + jlog("offline", "endpoint=%s reason=connect_failed hold_s=%.0f", ep->name, CFG.offline_hold_s); + 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, out_model, need, retry, use_hooks); + if (ready == -2) { + ep->offline_until = now_s() + CFG.offline_hold_s; + jlog("offline", "endpoint=%s reason=vanished", ep->name); + strncat(attempts, " vanished", sizeof attempts - strlen(attempts) - 1); + continue; + } + 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; + } + + ep->inflight++; + double started = now_s(); + int rc = forward(fd, ep, rq.method, rq.path, rq.headers, out_body, out_len, need); + ep->inflight--; + if (rc == 0) { + ep->ok_count++; + ep->last_ms = (long)((now_s() - started) * 1000.0); + jlog("served_by", "endpoint=%s ms=%ld need_tokens=%ld rule_line=%d", + ep->name, ep->last_ms, need, rule->line); + free(rewritten); free(rq.body); free(hdr); + return; + } + ep->fail_count++; + ep->cooldown_until = now_s() + ep->cooldown_s; + jlog("failed", "endpoint=%s error=%s", ep->name, + ep->last_error[0] ? ep->last_error : "forward_error"); + strncat(attempts, " failed", sizeof attempts - strlen(attempts) - 1); + } + + char body[1024]; + snprintf(body, sizeof body, + "{\"error\":\"no_endpoint_available\",\"need_tokens\":%ld,\"rule_line\":%d,\"attempts\":\"%s\"}", + need, rule->line, attempts[0] ? attempts + 1 : "none"); + send_simple(fd, 503, "Service Unavailable", body); + free(rewritten); free(rq.body); free(hdr); +} + +/* ---------------------------------------------------------------------- main */ +int main(int argc, char **argv) +{ + const char *config_path = NULL; + int port_override = 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 { + fprintf(stderr, "usage: junction --config [--port N]\n"); + return 2; + } + } + if (!config_path) { + fprintf(stderr, "usage: junction --config [--port N]\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; + } + if (port_override) CFG.listen_port = port_override; + + signal(SIGPIPE, SIG_IGN); + + 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) { + fprintf(stderr, "cannot resolve %s:%d\n", 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); + if (!bind(lfd, ai->ai_addr, ai->ai_addrlen) && !listen(lfd, 32)) break; + close(lfd); + lfd = -1; + } + freeaddrinfo(res); + if (lfd < 0) { + fprintf(stderr, "cannot listen on %s:%d: %s\n", CFG.listen_host, CFG.listen_port, + strerror(errno)); + return 1; + } + jlog("listening", "addr=%s:%d endpoints=%d rules=%d", CFG.listen_host, CFG.listen_port, + CFG.endpoint_count, CFG.rule_count); + + for (;;) { + int cfd = accept(lfd, NULL, NULL); + if (cfd < 0) { if (errno == EINTR) continue; break; } + handle_client(cfd); + close(cfd); + } + close(lfd); + return 0; +} diff --git a/systemd/junction.service b/systemd/junction.service new file mode 100644 index 0000000..8fead51 --- /dev/null +++ b/systemd/junction.service @@ -0,0 +1,24 @@ +[Unit] +Description=junction — policy router for model endpoints +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +# Runs as an unprivileged user: it needs no privileges to proxy HTTP. +User=junction +Group=junction +EnvironmentFile=-/etc/junction/env +ExecStart=/usr/local/bin/junction --config /etc/junction/junction.conf +Restart=always +RestartSec=5 +# hardening: the process only needs its config and network +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadOnlyPaths=/etc/junction +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX + +[Install] +WantedBy=multi-user.target diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..da9568e --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,209 @@ +#!/bin/bash +# junction test suite — stub endpoints only, no network, no models. ~30 s. +set -uo pipefail +cd "$(dirname "$0")/.." +TMP=$(mktemp -d) +PORT=8099 +P_FAIL=9990; P_GATED=9991; P_DEAD=9992; P_SLOW=9993 +PIDS=() +FAILED=0 + +cleanup() { + for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null; done + rm -rf "$TMP" +} +trap cleanup EXIT + +ok() { printf ' OK %s\n' "$1"; } +bad() { printf ' FAIL %s\n' "$1"; FAILED=1; } +contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } + +make -s >/dev/null || { echo "build failed"; exit 1; } +[ -x tests/stub ] || cc -std=c99 -O2 -o tests/stub tests/stub.c || exit 1 + +tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!) +tests/stub $P_GATED "GATED" & PIDS+=($!) +tests/stub $P_SLOW "SLOW" --delay 6 & PIDS+=($!) +sleep 0.5 + +# a hook that refuses until a marker file exists (created after 3 s) +cat > "$TMP/gate.sh" < "$TMP/open" ) & +PIDS+=($!) + +cat > "$TMP/junction.conf" < "$TMP/router.log" 2>&1 & +PIDS+=($!) +sleep 0.7 + +REQ='{"model":"x","messages":[{"role":"user","content":"hi"}],"max_tokens":64}' + +echo "== 1. dead -> offline, failing -> cooldown, gated waits for its hook ==" +R1=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \ + "http://127.0.0.1:$PORT/v1/chat/completions") +contains "$R1" "served by GATED" "served by the gated endpoint once the hook opened" +grep -q "offline endpoint=dead" "$TMP/router.log" && ok "unreachable endpoint marked offline" \ + || bad "unreachable endpoint marked offline" +grep -q "failed endpoint=failing" "$TMP/router.log" && ok "503 endpoint cooled down" \ + || bad "503 endpoint cooled down" +grep -q "waiting endpoint=gated" "$TMP/router.log" && ok "hook refusal retried, not fatal" \ + || bad "hook refusal retried, not fatal" + +echo "== 2. /status ==" +ST=$(curl -s -m 5 "http://127.0.0.1:$PORT/status") +contains "$ST" '"name":"dead"' "status lists endpoints" +OFF=$(printf '%s' "$ST" | sed -n 's/.*"name":"dead"[^}]*"offline_s":\([0-9]*\).*/\1/p') +if [ -n "$OFF" ] && [ "$OFF" -gt 0 ]; then ok "dead endpoint holds an offline window (${OFF}s)"; else bad "offline_s=$OFF"; fi + +echo "== 3. slow endpoint, forced: 'still_working' must be logged ==" +curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/pause/gated" >/dev/null +: > "$TMP/router.log" +R3=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \ + "http://127.0.0.1:$PORT/v1/chat/completions") +contains "$R3" "served by SLOW" "slow endpoint served" +grep -q "still_working side=upstream" "$TMP/router.log" && ok "silence logged as still_working" \ + || bad "silence logged as still_working" +curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/resume/gated" >/dev/null + +echo "== 4. rules: block, catch-all, context threshold ==" +cat > "$TMP/rules.conf" <100000 pass big +req for "blocked-*" block +req for "*" pass small +CFG +./junction --config "$TMP/rules.conf" > "$TMP/rules.log" 2>&1 & +PIDS+=($!) +sleep 0.7 + +R4a=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"blocked-model","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$((PORT+1))/v1/chat/completions") +contains "$R4a" "blocked_by_rule" "block rule refuses" + +R4b=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"anything","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$((PORT+1))/v1/chat/completions") +contains "$R4b" "served by GATED" "catch-all rule serves through the small endpoint" + +echo "== 5. model rewrite ('pass as ') ==" +cat > "$TMP/rewrite.conf" < "$TMP/rewrite.log" 2>&1 & +PIDS+=($!) +sleep 0.7 + +R5=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"original-name","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$((PORT+2))/v1/chat/completions") +contains "$R5" "served by GATED" "rewrite rule still serves" +grep -q "served_by endpoint=echo" "$TMP/rewrite.log" && ok "rewrite logged a served_by line" \ + || bad "rewrite logged a served_by line" + +echo "== 6. no rule matches -> 503, fast ==" +cat > "$TMP/norule.conf" <100000 pass small +CFG +./junction --config "$TMP/norule.conf" > "$TMP/norule.log" 2>&1 & +PIDS+=($!) +sleep 0.7 +T0=$(date +%s%N) +R6=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' -d "$REQ" \ + "http://127.0.0.1:$((PORT+3))/v1/chat/completions") +MS=$(( ($(date +%s%N) - T0) / 1000000 )) +contains "$R6" "no_matching_rule" "unmatched request refused" +if [ "$MS" -lt 2000 ]; then ok "refusal in ${MS} ms"; else bad "refusal took ${MS} ms"; fi + +echo "== 7. config errors are loud ==" +printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n timout 5\n}\n' > "$TMP/bad.conf" +OUT=$(./junction --config "$TMP/bad.conf" 2>&1) +contains "$OUT" "unknown endpoint keyword 'timout'" "typo in an endpoint key is an error" +printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n}\nreq for "*" pass nope\n' > "$TMP/bad2.conf" +OUT2=$(./junction --config "$TMP/bad2.conf" 2>&1) +contains "$OUT2" "unknown endpoint 'nope'" "a rule may not pass to an unknown endpoint" + +echo +if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi +exit "$FAILED" diff --git a/tests/stub.c b/tests/stub.c new file mode 100644 index 0000000..349651d --- /dev/null +++ b/tests/stub.c @@ -0,0 +1,97 @@ +/* tests/stub.c — a stub OpenAI-compatible endpoint for the test suite. + * + * stub [--fail] [--delay SECONDS] + * + * --fail always answers 503 (an endpoint that is up but will not serve) + * --delay waits that long before answering (to exercise "still_working") + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include + +static void send_all(int fd, const char *buf, size_t len) +{ + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, buf + off, len - off); + if (n <= 0) return; + off += (size_t)n; + } +} + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "usage: stub [--fail] [--delay SECONDS]\n"); + return 2; + } + int port = atoi(argv[1]); + const char *name = argv[2]; + int fail = 0; + double delay = 0; + 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]); + } + + 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)" : ""); + + for (;;) { + int cfd = accept(lfd, NULL, NULL); + if (cfd < 0) continue; + + char req[8192]; + ssize_t n = read(cfd, req, sizeof req - 1); + if (n <= 0) { close(cfd); continue; } + req[n] = '\0'; + + if (delay > 0) { + struct timespec ts = { (time_t)delay, (time_t)((delay - (time_t)delay) * 1e9) }; + nanosleep(&ts, NULL); + } + + char body[512]; + 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, "GET", 3)) { + char b[256]; + 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\nConnection: close\r\n\r\n%s", strlen(b), b); + } else { + char b[320]; + 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\nConnection: close\r\n\r\n%s", strlen(b), b); + } + send_all(cfd, body, strlen(body)); + close(cfd); + } +}