Files
junction/examples/full-reference.conf
T
Hermes c8b4e51a16 Cluster: mehrere Instanzen auf einem Port, Drain bei SIGTERM, gemeinsamer Cache
Drei Teile, die zusammengehören, ohne dass ein Dienst dazwischen nötig wäre.

so_reuseport: mehrere Instanzen binden dieselbe Adresse, der Kernel verteilt. Zusammen
mit dem neuen Drain ergibt das ein Rolling Update — die neue Instanz nimmt Verkehr an,
während die alte noch bedient. SIGTERM schließt zuerst den Listener, bedient Laufendes
fertig und beendet dann; ein Request, der nach drain_timeout (Standard 15 s) noch hängt,
wird verworfen und geloggt. Vorher war SIGTERM ein Abbruch mitten in der Antwort.
packaging/junction@.service macht daraus zwei Befehle (start junction@blue, stop
junction@green); auf n95 durchgespielt: zwei Listener auf einem Port, blue loggt
draining/drained, green antwortet weiter mit 200.

Gemeinsamer Cache ohne Redis: jeder Knoten gibt seinen Speicher über einen eigenen Port
aus, cache_peer fragt ihn bei einem lokalen Fehlschlag, ein Fill wird asynchron
weitergereicht (höchstens vier gleichzeitig, ein verworfener Push ist kein Fehler). Der
Transport ist eine kleine HTTP-Teilmenge mit einem Rahmen aus zwei 32-Bit-Längen —
Head und Body so, wie der Knoten sie gesendet hätte. Ein Treffer beim Nachbarn landet
mit der Restlaufzeit lokal, damit der nächste Aufruf nicht wieder fragt. Ohne
cache_secret_env öffnet der Port gar nicht erst.

Zwei echte Funde dabei: SO_REUSEPORT ist unter -D_POSIX_C_SOURCE=200809L nicht
deklariert, ein #ifdef darum kompiliert stillschweigend weg (Symptom: "Address already
in use" trotz so_reuseport on) — der Makefile setzt jetzt -D_DEFAULT_SOURCE. Und ein
Peer-Aufruf ohne Half-Close lässt den Nachbarn auf seinen Empfangs-Timeout warten,
womit jeder Lookup in den 150 ms verhungert und der Mesh wie kaputt aussieht.

--check prüft die Konfiguration jetzt wirklich, ohne zu binden (stand schon als
Behauptung in den Beispielen).

Tests: neuer Abschnitt 33/34 (15 Prüfungen, eigener Portbereich PORT+200…207):
Peer-Treffer ohne Anbieter-Aufruf, Geheimnis erzwungen, fehlendes Geheimnis = kein
Port, stiller Peer kostet genau den Timeout (203 ms gemessen), zwei Instanzen auf einem
Port, Drain, Übergabe ohne Ausfall, exclusiver Port ohne so_reuseport.
make test: PASS, 210 Prüfungen, 154 s.
2026-11-08 09:08:43 +00:00

457 lines
18 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ============================================================================
# junction — full reference configuration
# ============================================================================
#
# This file contains EVERY key the parser knows, each with an explanation and a
# sensible value. It is meant to be copied from: for production, delete the
# endpoints you do not need, not the explanations.
#
# Grammar: keyword, arguments, braces. `#` starts a comment, double quotes group
# words. An unknown keyword is a hard error with a line number — there are no
# silent typos.
#
# Check without starting: junction --config this-file --check
# ============================================================================
# ---------------------------------------------------------------- listener
#
# Where junction listens. Plain HTTP without `tls`. With `tls`, two certificate
# paths in this order: certificate, key.
#
# Loopback is the right choice when the process holds real upstream keys in its
# environment — then it is not an open proxy for LAN or VPN.
listen 127.0.0.1:8090
# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
# Prefix of every log line. It lives here so no product name appears in the code.
log_prefix junction
# ---------------------------------------------------------------- time limits
#
# Connecting to the endpoint. A failure here means "offline" immediately — that is
# not a retry case, a machine that does not answer does not get better by asking
# twice.
connect_timeout_ms 1500
# How long an endpoint counts as offline after a connect failure, before the next
# attempt probes it again. Seconds.
offline_hold_s 20
# Upper bound for a request body. Protection against a client using the router as
# storage.
max_body_bytes 67108864
# ---------------------------------------------------------------- concurrency
#
# How many requests may be on their way to upstreams at the same time. The rest
# wait in line instead of being refused.
max_inflight 8
# How long a waiting request may stand in line before it gets an answer. Seconds.
# Afterwards: an error event, followed by [DONE] for streamers.
queue_timeout 300
# A second attempt before the chain moves on. 429/408/5xx are often over in
# seconds; the next link costs money or context instead. Connect failures are NOT
# retried (those mean offline, that is what the hooks are for), and nothing is
# retried after the streaming head has gone out. Retry-After is not evaluated.
retry_num 1
retry_backoff 0.5
# Whole chain offline? A request may wait this long instead of getting a 503 at
# once. In the van the uplink is often gone for seconds. Deliberately before the
# queue slot: a request that waits holds no upstream place. 0 = do not wait.
offline_wait 20
# ---------------------------------------------------------------- monitoring
#
# A second listener that answers GET /metrics and nothing else. Prometheus runs in
# a container here and cannot reach the host's loopback; instead of putting /v1 and
# /admin on the network, there is exactly this one read-only port.
metrics tcp 192.168.1.148:9180
# ---------------------------------------------------------------- cluster
#
# Several instances on one port and one cache shared between them — no Redis, no
# etcd, no proxy in front. Both halves are optional and independent.
#
# so_reuseport: the kernel distributes the connections over the instances that bound
# the same address. A new instance takes traffic while the old one still serves.
#
# drain_timeout: on SIGTERM the listening socket is closed first, the running requests
# are finished, then the process exits. A request still running after this many seconds
# is abandoned (logged as drain_timeout) — an update must not hang on an upstream.
so_reuseport on
drain_timeout 15
# The cache peer port of THIS instance. It answers three paths and nothing else:
# GET /cache/<16 hex> a cached response (head and body, framed)
# PUT /cache/<16 hex> store one (pushed by another instance)
# GET /cache/stats its own counters
# Without cache_secret_env this port does not open at all: an unprotected peer port on
# a LAN is a way to read responses you never paid for, and to fill someone's memory.
cache tcp 127.0.0.1:8170
cache_secret_env JUNCTION_CACHE_KEY
# The other instances, asked on a local miss and pushed to on a fill. Repeated line per
# peer. cache_peer_timeout_ms is the entire cost of a peer that accepts and then says
# nothing; 150 ms is a LAN round trip with room to spare.
cache_peer 127.0.0.1:8171
cache_peer_timeout_ms 150
# ---------------------------------------------------------------- guard
#
# A command that sees every request before it is routed: exit 0 = let it through,
# anything else = 403 with stdout as the reason. junction brings no content rule of
# its own. The body arrives as a file (JUNCTION_BODY_FILE), not on stdin — a script
# that reads only part of it would otherwise hang writing into a full pipe.
#
# Only the request is inspected. Inspecting the answer would mean buffering every
# stream — exactly what this router does not do.
#
# guard request cmd "/home/lotherk/.hermes/scripts/guard.sh"
# ---------------------------------------------------------------- response cache
#
# Memory only, LRU, key is method + path + model + body. Streams are never cached.
# The upstream's `Cache-Control: no-store/private` and the client's `no-cache` are
# respected.
#
# 0 means: cache off. A cache on a router that serves models at different
# temperatures is usually wrong — hence off here.
cache_ttl 0
cache_entries 0
cache_bytes 0
# Only cache requests whose answer is predictable: temperature 0, or an embedder
# (the same text always gives the same vector). Caching an answer with temperature
# 0.7 would hand the second caller someone else's answer — that is not a saving,
# it is a wrong answer.
cache_deterministic_only on
# ---------------------------------------------------------------- prompt size
#
# Characters per token for the estimate that `ctx` rules use. 0 (default) means: no
# estimate, and a rule with a ctx condition is refused at load time — an error beats
# a rule that silently never matches.
#
# The value is an assumption about tokenisation, not a measurement. Base64 image
# data is skipped when counting, otherwise a photo counts as a hundred thousand
# tokens.
ctx_chars_per_token 4
# ---------------------------------------------------------------- selection order
#
# How targets INSIDE one rule are ordered when several are named:
# first in the order of the rule (plain failover)
# round-robin in turns, evenly
# least-usage smallest own consumption first (percent of budget)
# cost consumption × price; in the off-peak window the price halves
balance cost
# ---------------------------------------------------------------- virtual keys
#
# Clients get these keys, never the real upstream key. The value lives in an
# environment file (0600 root); here stands only the name of the variable.
#
# vkey "name" token_env VAR allow "<model-glob>" [endpoints "a,b"] [rpm N] [budget USD]
#
# `allow` limits the models, `endpoints` additionally the targets. A key that may
# only use DeepSeek cannot trigger a GPT call, even if a rule would allow it.
#
# rpm and budget limit the consumption of ONE client (not the provider's): above rpm
# junction answers 429 with Retry-After, above budget 403. The budget is per calendar
# month and is recomputed from the spend log at startup — without that it would be
# full again after every restart.
vkey "webui" token_env VKEY_WEBUI allow "deepseek-*" rpm 60 budget 10
vkey "navigator" token_env VKEY_NAVIGATOR allow "*" endpoints "ollama1,ollama2" rpm 30 budget 5
vkey "hermes" token_env VKEY_HERMES allow "*"
# Bookkeeping: one JSON line per request that reported usage. Without this file
# there is no monthly figure and no budget that survives a restart.
spend_log /var/lib/junction/spend.jsonl
# ============================================================================
# Endpoints
# ============================================================================
# ---------------------------------------------------------------- subscription cloud
#
# The most expensive path per request, but already paid for: the marginal cost is
# nearly zero. `cost` here is a comparison weight, not a sum of money.
endpoint cloud {
base https://opencode.ai/zen/go/v1
kind cloud
context 200000
# Lower number wins when a rule names several targets without an order of its
# own. Only relevant with balance first.
priority 90
# Total time for one request and the silence until "still_working" appears in
# the log. Two values, because a thinking model is not hanging.
timeout 900
idle_timeout 120
# Its own connect limit: this target sits behind a tunnel, a failed connect
# should pass the chain on after 400 ms, not after 1.5 s.
connect_timeout_ms 400
tls_verify on
api_key_env OPENCODE_GO_API_KEY
# Some upstreams behind Cloudflare refuse foreign user agents (403/1010) and
# want a session id. header may be repeated.
header "User-Agent: Mozilla/5.0 (X11; Linux x86_64) Olivia-UI/1.0"
header "x-opencode-session: ses-olivia-webui"
# Measure consumption from outside: the script prints one number, junction
# polls it.
usage_cmd /home/lotherk/.hermes/scripts/junction_usage_opencode.sh
usage_poll 120
# Soft and hard limit in percent. Above soft the request is slowed, above hard
# the endpoint is skipped — but only when a rule names another target.
budget soft 85
budget hard 96
on_soft delay 2
on_hard skip
cost 0.1
cache off
}
# ---------------------------------------------------------------- credit cloud, two accounts
#
# Two accounts of the same provider, each with its own monthly credit. Both
# endpoints look alike; they differ only in key, usage measurement and priority.
# Weight: higher = more often. Under round-robin a target with weight 3 gets three
# slots in the round; under cost/least-usage its consumption counts one third.
endpoint ollama1 {
weight 3
base https://ollama.com/v1
kind cloud
context 128000
priority 50
timeout 900
idle_timeout 120
tls_verify on
api_key_env OLLAMA_KEY1
usage_cmd "/home/lotherk/.hermes/scripts/junction_usage_ollama.sh 1"
usage_poll 180
budget soft 80
budget hard 95
on_soft delay 1
on_hard skip
# Window in which this endpoint is cheaper: from 18:00 to 12:00 of the following
# day. One window, not two — "all weekend" cannot be expressed with it.
offpeak 18:00-12:00
cost 1.5
}
endpoint ollama2 {
base https://ollama.com/v1
kind cloud
# Two accounts as two endpoints: that keeps the quota per account visible
# (usage_cmd 1 vs. 2). As one endpoint with two api_key_env lines junction would
# rotate to the second account on a 429, but usage_cmd and /api/show would only
# run with the first key — the second account's quota would stay invisible.
context 128000
priority 50
timeout 900
idle_timeout 120
tls_verify on
api_key_env OLLAMA_KEY2
usage_cmd "/home/lotherk/.hermes/scripts/junction_usage_ollama.sh 2"
usage_poll 180
budget soft 80
budget hard 95
on_soft delay 1
on_hard skip
offpeak 18:00-12:00
cost 1.5
}
# ---------------------------------------------------------------- local machine with wake-up
#
# The interesting case: a workstation that sleeps. `wake` runs once before the hooks
# are repeated — wake first, then wait.
endpoint workstation {
base http://192.0.2.20:8080/v1
kind local
context 128000
priority 10
timeout 1800
idle_timeout 30
# Hook: exit 0 means usable, anything else "not yet". The reason the hook prints
# on stdout lands in /status and in the 503 body.
hook /usr/local/share/junction/hooks/check-http.sh
# How long to wait for the machine in total, and at what interval.
hook_retry 180
hook_backoff 5
# One wake-up call before the first repeat.
wake /usr/local/share/junction/hooks/wake-wol.sh
# Static header addition per endpoint.
header "X-Box: workstation"
# Can this endpoint read images? on = yes, off = no, omit = no check.
# A text endpoint is skipped for an image request instead of accepting it and
# answering with empty content.
vision off
# A local machine costs electricity, not money. Small weight so it wins the
# comparison while it is awake.
cost 0.0
cache on
tls_verify off
}
# ---------------------------------------------------------------- private TLS with its own CA
endpoint private-tls {
base https://llm.internal.example/v1
kind remote
context 32000
priority 30
timeout 600
idle_timeout 90
cooldown 120
tls_verify on
tls_ca /etc/junction/ca/internal-ca.pem
api_key_env INTERNAL_KEY
cache on
}
# ---------------------------------------------------------------- opencode serve
#
# opencode does not speak the OpenAI protocol: its API is session-oriented
# (/api/session, /prompt, /model, /message). With `kind opencode` junction translates
# in both directions, so a client keeps speaking /v1/chat/completions.
#
# Two values come from commands because opencode does not pin them: the background
# service binds a free port, and it creates a new password on every start.
endpoint opencode {
base http://127.0.0.1:4096
kind opencode
context 200000
timeout 600
idle_timeout 120
auth_basic opencode
pass_cmd /home/lotherk/.hermes/scripts/opencode_password.sh
# Only needed when the service runs on a random port:
# base_cmd "/home/lotherk/.opencode/bin/opencode service status"
cost 0.0
}
# ---------------------------------------------------------------- embedder, small and cheap
endpoint embed {
base http://192.168.1.116:11434/v1
kind local
context 8192
priority 10
timeout 120
idle_timeout 45
# After a failure, pause this many seconds instead of running into a timeout
# again on every request.
cooldown 30
cache on
}
# ============================================================================
# Rules — first match wins
# ============================================================================
#
# req [for <model-glob>] [path <glob>] [need >N | <N | N]
# [check hooks|none] [retry <s>]
# ( pass <target>[,<target>...] [as <model>] | block )
#
# for — model name from the request body, fnmatch pattern
# path — path, fnmatch pattern
# need — the output budget the client DECLARES (max_tokens /
# max_completion_tokens). No guessing, no character counting: a request
# that states nothing matches no need rule. >64000 means "more than 64k
# requested"; an endpoint with a smaller context is then skipped.
# check — hooks (the endpoint's default) or none (skip hooks, e.g. for model
# lists that make sense even when nothing is running)
# retry — wait time for hooks, overrides this rule's hook_retry
# as — rewrites the model field ONLY for that target. The first target gets the
# local id, the last the requested one.
# Model list: no hook needed, a sleeping machine answers it too.
req path "/v1/models" check none pass cloud
# Embedders run locally, no matter what else applies.
req for "*embed*" check none pass embed
# The free opencode models go to the opencode endpoint, nothing else does.
req for "opencode/*" pass opencode
req for "*-free" pass opencode
# Image requests: always to the image model, independent of the requested name.
# First the own machine (costs nothing), then the cloud — there with a rewritten
# model name. "as" applies to the target directly before it, not to the whole rule.
req vision pass workstation, cloud as "vision-capable-model"
# Small requests to the own machine, medium ones to the credit account, large ones to
# the subscription with the big context. Order matters: narrowest window first,
# otherwise the larger one catches everything. The numbers are policy and belong
# here, not in the code.
req ctx <2000 pass workstation
req ctx <50000 pass ollama1, cloud
req ctx >50000 pass cloud
# Large budgets cannot be held by the local machine — so do not send them there.
req need >64000 pass cloud, ollama1
# A model that only exists locally, with a local name; otherwise the same request is
# passed on to the cloud.
req for "*coder*" retry 300 pass workstation as "qwen3.8-flash-next-q1m", cloud
# A model that must not exist. 403, not a silent redirect.
req for "blocked-*" block
# Everything else: first the awake local machine, then the cloud, then credits.
# No match for a request means 503 no_matching_rule — a gap in the configuration is
# not a case for "send it somewhere".
# Give chains a name. A pool may point at another pool; it is resolved at load time,
# so a rule does not have to spell out five targets every time.
pool lokal ollama1, ollama2
pool alles cloud, lokal
# An endpoint may also fit on one line when it is small:
# endpoint kurz { base http://127.0.0.1:8080/v1; timeout 60 }
# This one rule wants plain failover, whatever the global setting is.
req for "starr*" balance first pass workstation, cloud
req for "*" check hooks pass workstation, cloud, ollama1, ollama2
# ============================================================================
# Control at runtime
# ============================================================================
#
# GET /status endpoints, counters, cache, rules, queue
# GET /metrics the same numbers as Prometheus text
# GET /spend[?month=YYYY-MM] cost per key and model, from the spend log
# POST /admin/pause/<name> stop routing there
# POST /admin/resume/<name> clear pause, cooldown and offline
# POST /admin/flush/cache drop every cached response body
#
# Everything else is forwarded to the endpoint the rules choose.
# Every response carries X-Junction-Endpoint, X-Junction-Ms and X-Junction-Cache.