Gewichtung, Balance pro Regel, Verbindungs-Zeitlimit pro Endpunkt

Drei Lücken, die eine echte Kette braucht:

  weight N              Endpunkte sind nicht gleich viel wert. Unter round-robin bekommt
                        ein Ziel so viele Plätze in der Runde, wie es wiegt; unter cost
                        und least-usage zählt sein Verbrauch nur 1/N.
  balance <modus>       in der Regel: eine Kette darf reines Failover wollen, während
                        global round-robin gilt.
  connect_timeout_ms    pro Endpunkt: ein Ziel hinter einem Tunnel braucht ein anderes
                        Limit als eines im eigenen LAN. 0 = global erben.

Geprüft mit zwei gesunden Stubs: Gewicht 3:1 verteilt 30 zu 10 über 40 Anfragen. Eine
Regel mit "balance first" bleibt bei sechs Anfragen sechsmal auf dem ersten Ziel, obwohl
global round-robin gilt. Ein unerreichbares Ziel mit eigenem Limit von 400 ms wird nach
414 ms übersprungen und die Kette geht weiter — statt 30 s zu warten.

Dazu eine Testkorrektur: die Logprüfung für TLS wartete nicht auf den Logschreiber und
meldete gelegentlich einen Fehler, der keiner war.

80 Prüfungen, keine Fehler.
This commit is contained in:
Hermes committed 2026-11-04 22:28:22 +00:00
1 parent ef0fa43661
commit 6325eb3bd6
7 files changed
+203 -10

No files matched your search

+2
View File
@@ -158,6 +158,8 @@ Endpoint:
| `kind` | free-form label (`local`, `remote`, `cloud`) |
| `priority` | lower wins when a rule lists several |
| `timeout` | total wall clock for one request (seconds) |
| `connect_timeout_ms` | per-endpoint connect limit; 0 = the global value |
| `weight` | 1..100, how often this endpoint is chosen (default 1) |
| `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) |
+10
View File
@@ -126,6 +126,10 @@ endpoint cloud {
timeout 900
idle_timeout 120
# Eigenes Verbindungs-Zeitlimit: dieses Ziel steht hinter einem Tunnel, ein
# ausgefallener Aufbau soll die Kette nach 400 ms weiterreichen, nicht nach 1,5 s.
connect_timeout_ms 400
tls_verify on
api_key_env OPENCODE_GO_API_KEY
@@ -154,7 +158,10 @@ endpoint cloud {
# Zwei Konten desselben Anbieters, je mit eigenem Monatsguthaben. Beide Endpunkte
# sind gleich aufgebaut; unterschieden werden sie nur durch Schlüssel, Verbrauchs-
# messung und Priorität.
# Gewicht: höher = häufiger. Unter round-robin bekommt ein Ziel mit Gewicht 3 drei
# Plätze in der Runde, unter cost/least-usage zählt sein Verbrauch nur ein Drittel.
endpoint ollama1 {
weight 3
base https://ollama.com/v1
kind cloud
context 128000
@@ -341,6 +348,9 @@ req for "blocked-*" block
# Alles Übrige: erst der wache lokale Rechner, dann die Cloud, dann Guthaben.
# Kein Treffer für eine Anfrage bedeutet 503 no_matching_rule — eine Lücke in der
# Konfiguration ist kein Fall für "irgendwohin schicken".
# Diese eine Regel will reines Failover, egal was global eingestellt ist.
req for "starr*" balance first pass workstation, cloud
req for "*" check hooks pass workstation, cloud, ollama1, ollama2
+24
View File
@@ -103,6 +103,8 @@ static void endpoint_defaults(j_endpoint *ep)
ep->offpeak_from = -1;
ep->offpeak_to = -1;
ep->cost_weight = 1.0;
ep->connect_timeout_ms = 0; /* 0 = global erben */
ep->weight = 1;
ep->vision = -1; /* nicht angegeben: keine Pruefung */
}
@@ -327,6 +329,17 @@ static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, s
else goto bad;
return 0;
}
if (!strcmp(k, "connect_timeout_ms")) {
if (n != 2 || as_double(w[1], &ep->connect_timeout_ms)) goto bad;
return 0;
}
if (!strcmp(k, "weight")) {
if (n != 2 || as_int(w[1], &ep->weight) || ep->weight < 1 || ep->weight > 100) {
snprintf(err, errlen, "line %d: weight must be 1..100", lineno);
return -1;
}
return 0;
}
if (!strcmp(k, "vision")) {
/* vision on|off — kann dieser Endpunkt Bilder verarbeiten? */
if (n != 2) goto bad;
@@ -394,6 +407,7 @@ static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t
r->ctx_min = -1;
r->ctx_max = -1;
r->vision = -1;
r->balance = -1; /* -1 = das globale Verfahren benutzen */
r->check = J_CHECK_INHERIT;
r->retry_s = -1;
r->line = lineno;
@@ -438,6 +452,16 @@ static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t
r->ctx_min = r->ctx_max = num;
}
i += 2;
} else if (!strcmp(k, "balance")) {
/* balance first | round-robin | least-usage | cost — nur für diese Regel */
if (i + 1 >= n) goto bad;
const char *m = w[i + 1];
if (!strcmp(m, "first")) r->balance = J_BALANCE_FIRST;
else if (!strcmp(m, "round-robin")) r->balance = J_BALANCE_RR;
else if (!strcmp(m, "least-usage")) r->balance = J_BALANCE_USAGE;
else if (!strcmp(m, "cost")) r->balance = J_BALANCE_COST;
else goto bad;
i += 2;
} else if (!strcmp(k, "vision")) {
r->vision = 1;
i++;
+7
View File
@@ -68,6 +68,12 @@ typedef struct {
int priority;
double timeout_s;
double idle_timeout_s;
/* 0 = das globale connect_timeout_ms benutzen. Ein Ziel hinter einem Tunnel braucht
* ein anderes Zeitlimit als eines im eigenen LAN — ein Wert für alle ist entweder
* zu großzügig für das eine oder zu knapp für das andere. */
double connect_timeout_ms;
/* Gewicht für die Auswahl: höher = häufiger bzw. bevorzugt. 1 ist neutral. */
int weight;
double cooldown_s;
double hook_retry_s;
double hook_backoff_s;
@@ -146,6 +152,7 @@ typedef struct {
long ctx_min; /* -1 = unset */
long ctx_max; /* -1 = unset */
int vision; /* -1 = egal, 0 = nur Text, 1 = nur mit Bild */
int balance; /* -1 = global, sonst J_BALANCE_* für diese Regel */
int check; /* J_CHECK_* */
double retry_s; /* <0 = inherit from endpoint */
+43 -9
View File
@@ -830,12 +830,19 @@ static int ep_in_offpeak(const j_endpoint *ep)
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 * (ep->cost_weight > 0 ? ep->cost_weight : 1.0);
return usage;
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"
@@ -843,12 +850,35 @@ static double ep_score(const j_endpoint *ep)
static void balance_order(const j_rule *r, int *order, int n)
{
static unsigned long rr_turn;
for (int i = 0; i < n; i++) order[i] = i;
if (CFG.balance == J_BALANCE_FIRST || n < 2) return;
/* Die Regel darf das Verfahren überschreiben; sonst gilt das globale. */
int mode = (r->balance >= 0) ? r->balance : CFG.balance;
if (CFG.balance == J_BALANCE_RR) {
int shift = (int)(rr_turn++ % (unsigned long)n);
for (int i = 0; i < n; i++) order[i] = (i + shift) % n;
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;
int shift = (int)(rr_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;
}
@@ -1183,7 +1213,8 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
j_conn up = J_CONN_INIT;
if (j_conn_open(&up, host, port, tls, tls ? ep->tls_verify : 0, ep->tls_ca,
CFG.connect_timeout_ms, err, errlen)) {
ep->connect_timeout_ms > 0 ? ep->connect_timeout_ms : CFG.connect_timeout_ms,
err, errlen)) {
free(rewritten);
return -1;
}
@@ -1603,7 +1634,10 @@ static void handle_client(j_conn *client)
if (vk && !vkey_allows_endpoint(vk, rule->targets[t])) continue;
order[norder++] = t;
}
if (CFG.balance != J_BALANCE_FIRST && norder > 1) balance_order(rule, order, norder);
{
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++) {
+108
View File
@@ -0,0 +1,108 @@
#!/bin/bash
# Wird von tests/run.sh eingebunden: Gewichtung, Balance pro Regel, Zeitlimits.
# Erwartet: $TMP, $PORT, $P_GATED, $P_FAIL, ok/bad/contains, ./junction
echo "== 19. Gewichtung, Balance pro Regel, Verbindungs-Zeitlimit =="
# Für die Verteilung braucht es ZWEI gesunde Ziele. GATED antwortet; ein zweiter Stub
# mit eigenem Namen kommt dazu, weil der vorhandene "FAILING" absichtlich ausfällt und
# dann immer das erste Ziel bedient würde.
BA=$P_GATED
BB=$((PORT+21))
BJ=$((PORT+23))
tests/stub $BB "ZWEIT" > /dev/null 2>&1 &
PIDS+=($!)
sleep 0.4
cat > "$TMP/bal.conf" <<CFG
listen 127.0.0.1:$BJ
connect_timeout_ms 2000
balance round-robin
endpoint stark {
base http://127.0.0.1:$BA/v1
weight 3
timeout 10
}
endpoint schwach {
base http://127.0.0.1:$BB/v1
weight 1
timeout 10
}
# Diese Regel will reines Failover, egal was global eingestellt ist.
req for "starr*" balance first pass stark, schwach
req for "*" pass stark, schwach
CFG
./junction --config "$TMP/bal.conf" > "$TMP/bal.log" 2>&1 &
PIDS+=($!)
sleep 0.8
# 1. Gewichtetes Reihum: 3:1 soll sich in der Verteilung zeigen
A=0; B=0
for i in $(seq 1 40); do
R=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' \
-d '{"model":"x","messages":[{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$BJ/v1/chat/completions")
case "$R" in
*"served by GATED"*) A=$((A+1));;
*"served by ZWEIT"*) B=$((B+1));;
esac
done
# Ein Ziel mit Gewicht 3 soll deutlich häufiger drankommen als eines mit Gewicht 1.
if [ "$A" -ge 24 ] && [ "$B" -ge 6 ]; then
ok "weighted round-robin: $A zu $B bei Gewicht 3:1"
else
bad "weighted round-robin verteilte $A zu $B, erwartet etwa 30 zu 10"
fi
# 2. balance first in der Regel schlägt das globale round-robin
FIRST=0
for i in $(seq 1 6); do
R=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' \
-d '{"model":"starr-modell","messages":[{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$BJ/v1/chat/completions")
case "$R" in *"served by GATED"*) FIRST=$((FIRST+1));; esac
done
if [ "$FIRST" -eq 6 ]; then
ok "a rule's own 'balance first' overrides the global round-robin"
else
bad "rule-level balance did not override the global mode ($FIRST/6 on the first target)"
fi
# 3. Verbindungs-Zeitlimit pro Endpunkt: ein unerreichbares Ziel darf die Kette nicht
# aufhalten, sondern muss schnell weiterreichen.
cat > "$TMP/conn.conf" <<CFG
listen 127.0.0.1:$((PORT+24))
connect_timeout_ms 30000
endpoint langsam {
base http://10.255.255.1:9/v1
connect_timeout_ms 400
timeout 30
}
endpoint gesund {
base http://127.0.0.1:$BA/v1
timeout 10
}
req for "*" pass langsam, gesund
CFG
./junction --config "$TMP/conn.conf" > "$TMP/conn.log" 2>&1 &
PIDS+=($!)
sleep 0.8
START=$(date +%s%N)
R=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \
-d '{"model":"x","messages":[{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$((PORT+24))/v1/chat/completions")
END=$(date +%s%N)
MS=$(( (END-START)/1000000 ))
contains "$R" "served by GATED" "the chain moves past an unreachable endpoint"
if [ "$MS" -lt 5000 ]; then
ok "the per-endpoint connect timeout fired after ${MS} ms, not the global 30 s"
else
bad "the per-endpoint connect timeout did not apply (${MS} ms)"
fi
+9 -1
View File
@@ -20,7 +20,7 @@ contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; }
# A leftover process on a test port produces confusing failures (a stale junction can
# answer requests with somebody else's config), so fail loudly and early.
for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 9443 9990 9991 9992 9993 9994 9995 9996; do
for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 9443 9990 9991 9992 9993 9994 9995 9996; do
if ss -tln 2>/dev/null | grep -q ":$port "; then
echo "port $port is busy — a leftover junction/stub is still running:"
ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /'
@@ -334,6 +334,10 @@ CFG
-d '{"model":"s","messages":[{"role":"user","content":"over tls"}],"max_tokens":8}' \
"http://127.0.0.1:$((PORT+6))/v1/chat/completions")
contains "$US" "served by SECURE" "request served by an https endpoint"
for _try in 1 2 3 4 5 6 7 8 9 10; do
grep -q "tls=1" "$TMP/tlsup.log" && break
sleep 0.1
done
grep -q "tls=1" "$TMP/tlsup.log" && ok "log marks the TLS connection" || bad "log marks the TLS connection"
# verification must actually be enforced: the same self-signed peer, tls_verify on
@@ -619,6 +623,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected"
# shellcheck source=tests/opencode.sh
. "$(dirname "$0")/opencode.sh"
# Gewichtung, Balance pro Regel und Zeitlimits.
# shellcheck source=tests/balancing.sh
. "$(dirname "$0")/balancing.sh"
echo
if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi
exit "$FAILED"