diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 93d4043..d23d880 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,6 +9,7 @@ on: - "go.mod" - "go.sum" - ".goreleaser.yaml" + - "Dockerfile.goreleaser" - ".gitattributes" - ".traefik.yml" - "version.go" @@ -25,4 +26,5 @@ jobs: uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main with: go-version: "1.26.x" + docker-enabled: true secrets: inherit diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 5d505d9..e028e4a 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,9 +1,36 @@ version: 2 -# Traefik plugins are source-only - no binary builds -# Traefik loads plugins via Yaegi interpreter at runtime +# Traefik loads the plugin from this repository's source under Yaegi, so the +# plugin form needs no binary. The build below is the standalone gateway +# (cmd/gateway), which runs behind a reverse proxy instead of inside Traefik. builds: - - skip: true + - id: llmgateway + main: ./cmd/gateway + binary: llmgateway + env: + - CGO_ENABLED=0 + - GOFLAGS=-mod=vendor + flags: + - -trimpath + ldflags: + - -s -w + - -X main.version={{ .Version }} + goos: + - linux + - darwin + goarch: + - amd64 + - arm64 + +archives: + - id: llmgateway + ids: + - llmgateway + formats: [tar.gz] + name_template: "llmgateway_v{{ .Version }}_{{ .Os }}_{{ .Arch }}" + files: + - LICENSE + - README.md # Source archive for GitHub releases, built with `git archive` under the # hood. `git archive` reads .gitattributes export-ignore at the archived @@ -60,3 +87,31 @@ signs: - "--yes" artifacts: checksum output: true + +dockers_v2: + - ids: + - llmgateway + images: + - "ghcr.io/lukaszraczylo/traefik-llmgateway" + tags: + - "{{ .Version }}" + - "latest" + platforms: + - linux/amd64 + - linux/arm64 + dockerfile: Dockerfile.goreleaser + labels: + "org.opencontainers.image.title": "llmgateway" + "org.opencontainers.image.version": "{{ .Version }}" + "org.opencontainers.image.source": "https://github.com/lukaszraczylo/traefik-llmgateway" + "org.opencontainers.image.description": "Standalone multi-provider LLM gateway, the compiled form of the traefik-llmgateway plugin" + "org.opencontainers.image.licenses": "MIT" + +docker_signs: + - cmd: cosign + artifacts: manifests + output: true + args: + - sign + - "${artifact}@${digest}" + - "--yes" diff --git a/Dockerfile b/Dockerfile index 8511760..50c4d29 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Image for deployment form (B): the standalone compiled binary -# (cmd/gateway), which runs BEHIND Traefik rather than inside it. Form (A), +# (cmd/gateway), which runs behind a reverse proxy rather than inside Traefik. Form (A), # the Yaegi-interpreted plugin, needs no image at all — Traefik loads this # repository's source directly — so nothing here affects it. # @@ -7,10 +7,9 @@ # reachable); .dockerignore keeps webui/node_modules, .git and the # integration fixtures out of the transfer. # -# Built locally, never in CI: `make docker-build`. This repository -# deliberately does not add GitHub Actions for it, and .goreleaser.yaml -# stays at `builds: - skip: true` because its job is publishing the plugin -# SOURCE tarball for the Traefik catalog, not producing binaries. +# This file builds the image from source for local use: `make docker-build`. +# Releases build the published image with GoReleaser instead +# (.goreleaser.yaml dockers_v2, Dockerfile.goreleaser). # --platform=$BUILDPLATFORM pins the toolchain to the BUILDER's native # architecture and cross-compiles from there via GOOS/GOARCH below. Without diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser new file mode 100644 index 0000000..3be11ae --- /dev/null +++ b/Dockerfile.goreleaser @@ -0,0 +1,10 @@ +# Image for the standalone gateway, built by GoReleaser (dockers_v2) from the +# binaries it already compiled: dist///llmgateway. `Dockerfile` +# builds the same image from source for local use (make docker-build). +FROM gcr.io/distroless/static-debian12:nonroot +ARG TARGETPLATFORM +COPY ${TARGETPLATFORM}/llmgateway /usr/local/bin/llmgateway +USER nonroot:nonroot +EXPOSE 8080 +ENTRYPOINT ["/usr/local/bin/llmgateway"] +CMD ["-config", "/etc/llmgateway/config.yaml"] diff --git a/README.md b/README.md index a0f5e9c..db01973 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ It runs in either of two forms from this one codebase — as a [Yaegi](https://github.com/traefik/yaegi)-interpreted Traefik middleware plugin, the same way [`traefikoidc`](https://github.com/lukaszraczylo/traefikoidc) does, configured per-middleware in Traefik's dynamic configuration; or as -a standalone compiled binary sitting behind Traefik. The plugin form needs +a standalone compiled binary behind any reverse proxy. The plugin form needs no sidecar and no companion service; the binary form exists because streaming arrives token-by-token there and buffered in the plugin. See [Deployment modes](#deployment-modes). @@ -99,12 +99,12 @@ together. | | **(A) Traefik plugin** | **(B) Standalone binary** | |---|---|---| -| How it runs | Yaegi-interpreted inside Traefik | compiled process behind Traefik | +| How it runs | Yaegi-interpreted inside Traefik | compiled process behind a reverse proxy | | Configured by | `Middleware` CR / dynamic config | a YAML or JSON config file | | **Streaming** | **buffered** ([why](#known-limitations)) | **incremental** | -| Config hot-reload | automatic, on CR change | restart the process | +| Config hot-reload | automatic, on CR change | automatic, on file change or SIGHUP ([how](#config-reload-in-the-binary)) | | Extra moving parts | none | one Deployment + Service + image | -| Catalog-supported | yes | build it yourself | +| Distribution | Traefik Plugin Catalog | release image and binaries ([below](#running-the-binary)) | **Form (A) is still the default** and nothing about it changed. Choose form (B) for one reason: SSE arrives token-by-token. Traefik hands the @@ -122,6 +122,20 @@ accounting, admin API and MCP/A2A proxy, and the same `literal` / ### Running the binary +Each release publishes a signed multi-arch image (linux/amd64, linux/arm64) +and `llmgateway_v__.tar.gz` binaries for linux and darwin. +GoReleaser builds both from `cmd/gateway`: + +```sh +docker run -p 8080:8080 -v "$PWD/config:/etc/llmgateway:ro" \ + ghcr.io/lukaszraczylo/traefik-llmgateway: +cosign verify ghcr.io/lukaszraczylo/traefik-llmgateway: \ + --certificate-identity-regexp 'https://github.com/lukaszraczylo/' \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com +``` + +To build from source: + ```sh make build-binary # -> bin/llmgateway make docker-build IMAGE=registry.example/llmgateway:v1 PLATFORMS=linux/amd64,linux/arm64 @@ -141,6 +155,8 @@ passed flag always beats the environment. | `-drain-delay` | `LLMGW_DRAIN_DELAY` | `5s` | | `-health-path` | `LLMGW_HEALTH_PATH` | `/healthz` | | `-ready-path` | `LLMGW_READY_PATH` | `/readyz` | +| `-reload-interval` | `LLMGW_RELOAD_INTERVAL` | `5s` (`0` turns polling off) | +| `-reload-drain-timeout` | `LLMGW_RELOAD_DRAIN_TIMEOUT` | `10m` | `-log-level` filters **only the binary's own lifecycle lines**. The gateway's own `INFO`/`WARN`/`ERROR` output is written unconditionally to @@ -150,6 +166,29 @@ The config file is the same structure as the plugin's `plugin.llmgateway` block, hoisted to the top level — so a `Middleware` CR's `spec.plugin.llmgateway` can be lifted into a `ConfigMap` unchanged. `.json` is accepted directly. +### Config reload in the binary + +The binary reads the config file every `-reload-interval` and on `SIGHUP`. +When the content changes, it builds a new gateway from the file. If that +succeeds, new requests go to the new gateway at once. Requests already +running finish on the old gateway, which then closes. A replaced gateway +that still has requests after `-reload-drain-timeout` closes anyway. +`-reload-drain-timeout` must be positive. + +- **A bad file changes nothing.** A file that does not parse, has an + unknown key or fails validation is logged at error level. The old + gateway keeps serving. The binary tries again on every check, because + the cause can be outside the file, such as a secret file that is not + mounted yet. It logs each distinct error once. +- **`SIGHUP` always rebuilds**, even when the content is unchanged. Use it + after you rotate a secret that a `file:/path` reference reads. +- **The check compares content, not timestamps.** A Kubernetes `ConfigMap` + mount, which swaps a symlink, reloads within one interval. +- **A rebuilt gateway starts with fresh in-process state.** Without Redis, + this resets the counters, breakers and learned limits. With Redis, they + are shared and survive. The users file (`usersFile`) reloads by itself + and needs no config change. + ### Things that differ from the plugin, and will bite you - **`metrics.allowedCIDRs` inverts from closed to open.** This is the one diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go index c60e1b5..8658bb1 100644 --- a/cmd/gateway/main.go +++ b/cmd/gateway/main.go @@ -1,5 +1,5 @@ // Command gateway runs the LLM gateway as a standalone compiled binary, -// sitting BEHIND Traefik rather than inside it. +// sitting behind a reverse proxy rather than inside Traefik. // // This is deployment form (B). Form (A) — the Yaegi-interpreted Traefik // middleware plugin — is unchanged and remains the default; both forms are @@ -74,6 +74,8 @@ const ( defaultReadHeaderWait = 10 * time.Second defaultIdleTimeout = 120 * time.Second defaultMaxHeaderBytes = 1 << 20 + defaultReloadEvery = 5 * time.Second + defaultReloadDrain = 10 * time.Minute ) // telemetryOptOutVars are the environment variables oss-telemetry itself @@ -105,6 +107,8 @@ type options struct { readyPath string shutdownWait time.Duration drainDelay time.Duration + reloadEvery time.Duration + reloadDrain time.Duration showVersion bool } @@ -135,10 +139,20 @@ func parseOptions(args []string, stderr *os.File) (*options, error) { fs.DurationVar(&o.drainDelay, "drain-delay", envDurationOr("LLMGW_DRAIN_DELAY", defaultDrainDelay), "how long to keep serving after readiness starts failing, so the load balancer can drop this "+ "endpoint before the listener closes [LLMGW_DRAIN_DELAY]") + fs.DurationVar(&o.reloadEvery, "reload-interval", envDurationOr("LLMGW_RELOAD_INTERVAL", defaultReloadEvery), + "how often to check the config file for changes; 0 turns polling off (SIGHUP still reloads) [LLMGW_RELOAD_INTERVAL]") + fs.DurationVar(&o.reloadDrain, "reload-drain-timeout", envDurationOr("LLMGW_RELOAD_DRAIN_TIMEOUT", defaultReloadDrain), + "how long a replaced gateway keeps running for its in-flight requests before it is closed [LLMGW_RELOAD_DRAIN_TIMEOUT]") fs.BoolVar(&o.showVersion, "version", false, "print this binary's version and exit") if err := fs.Parse(args); err != nil { return nil, err } + if o.reloadEvery < 0 { + return nil, fmt.Errorf("-reload-interval must not be negative, got %s", o.reloadEvery) + } + if o.reloadDrain <= 0 { + return nil, fmt.Errorf("-reload-drain-timeout must be positive, got %s", o.reloadDrain) + } if o.healthPath == o.readyPath { return nil, fmt.Errorf("-health-path and -ready-path must differ (both are %q)", o.healthPath) } @@ -219,30 +233,13 @@ func run() error { } log := newLogger(opts.logLevel) - cfg, err := loadConfig(opts.configPath) + raw, err := os.ReadFile(opts.configPath) if err != nil { - return err + return fmt.Errorf("read config: %w", err) } log.info("starting version=%s name=%s config=%s listen=%s", version, opts.name, opts.configPath, opts.listenAddr) logTelemetryOptOut(log) - // passthroughUnknown routes an unrecognized path to the `next` - // handler. In form (A) that is the Traefik router's own backing - // service; in form (B) Traefik is IN FRONT of this process and there - // is no downstream at all, so the flag cannot mean what it means in - // the plugin. This is a warning rather than a hard error because the - // terminal handler below keeps the behaviour well-defined (a clean - // 404) — an operator carrying a working plugin config across should - // not be blocked, only told. - if cfg.PassthroughUnknown { - log.warn("passthroughUnknown is set, but a standalone binary has no downstream to pass through to: " + - "unknown routes return 404. Route non-gateway paths in Traefik instead.") - } - - if msg, warn := metricsCIDRWarning(cfg); warn { - log.warn(msg) - } - // signal.NotifyContext, not context.Background(): New blocks on the // registry's synchronous warm-fill, which with a large provider set // can run for minutes before the listener ever opens. A SIGTERM @@ -251,9 +248,10 @@ func run() error { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() - handler, err := traefikllmgateway.New(ctx, terminalHandler(), cfg, opts.name) + build := gatewayBuilder(ctx, opts.configPath, opts.name, log) + handler, err := build(raw) if err != nil { - return fmt.Errorf("construct gateway: %w", err) + return err } if ctx.Err() != nil { log.info("signal received during startup; exiting before serving") @@ -261,10 +259,13 @@ func run() error { return nil } + sw := &swapHandler{} + sw.cur.Store(newGeneration(handler, func() { closeGateway(handler, log) })) + var ready atomic.Bool srv := &http.Server{ Addr: opts.listenAddr, - Handler: withHealth(handler, &ready, opts.healthPath, opts.readyPath), + Handler: withHealth(sw, &ready, opts.healthPath, opts.readyPath), // Bounds a Slowloris header trickle (and satisfies gosec G112). ReadHeaderTimeout: defaultReadHeaderWait, // ReadTimeout and WriteTimeout are BOTH deliberately zero. @@ -311,12 +312,23 @@ func run() error { go func() { errCh <- srv.ListenAndServe() }() log.info("listening on %s (health %s, ready %s)", opts.listenAddr, opts.healthPath, opts.readyPath) + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + defer signal.Stop(hup) + reloadDone := make(chan struct{}) + go func() { + defer close(reloadDone) + newReloader(opts.configPath, raw, build, sw, opts.reloadDrain, log).run(ctx, opts.reloadEvery, hup) + }() + select { case err := <-errCh: // ErrServerClosed only ever arrives after a Shutdown this // function did not start, so reaching it here is a real failure. if !errors.Is(err, http.ErrServerClosed) { - closeGateway(handler, log) + stop() + <-reloadDone + sw.closeCurrent() return fmt.Errorf("listen on %s: %w", opts.listenAddr, err) } return nil @@ -347,6 +359,9 @@ func run() error { log.error("shutdown: %v", err) } + // The reloader exits on ctx; waiting for it means no swap lands after the close below. + <-reloadDone + // STRICTLY after Shutdown returns. Close releases the pooled Redis // connections shared by the limiter's store and the response cache; // closing them while requests are still draining would pull Redis out @@ -354,11 +369,31 @@ func run() error { // default those requests would silently fall back to in-process // counters rather than fail — a correctness regression invisible in // the logs. - closeGateway(handler, log) + sw.closeCurrent() log.info("stopped") return nil } +// logConfigWarnings logs the config settings that mean something else, or nothing, in a standalone binary. +func logConfigWarnings(cfg *traefikllmgateway.Config, log *logger) { + // passthroughUnknown routes an unrecognized path to the `next` + // handler. In form (A) that is the Traefik router's own backing + // service; in form (B) Traefik is IN FRONT of this process and there + // is no downstream at all, so the flag cannot mean what it means in + // the plugin. This is a warning rather than a hard error because the + // terminal handler below keeps the behaviour well-defined (a clean + // 404) — an operator carrying a working plugin config across should + // not be blocked, only told. + if cfg.PassthroughUnknown { + log.warn("passthroughUnknown is set, but a standalone binary has no downstream to pass through to: " + + "unknown routes return 404. Route non-gateway paths in Traefik instead.") + } + + if msg, warn := metricsCIDRWarning(cfg); warn { + log.warn(msg) + } +} + // closeGateway releases the Gateway's pooled resources when the handler // New returned exposes Close. // @@ -480,6 +515,12 @@ func loadConfig(path string) (*traefikllmgateway.Config, error) { if err != nil { return nil, fmt.Errorf("read config: %w", err) } + return decodeConfig(path, raw) +} + +// decodeConfig decodes raw the way loadConfig does. path picks the format by its extension and names errors. +func decodeConfig(path string, raw []byte) (*traefikllmgateway.Config, error) { + var err error doc := raw if !strings.EqualFold(filepath.Ext(path), ".json") { if doc, err = yamlToJSON(raw); err != nil { diff --git a/cmd/gateway/reload.go b/cmd/gateway/reload.go new file mode 100644 index 0000000..2703a63 --- /dev/null +++ b/cmd/gateway/reload.go @@ -0,0 +1,214 @@ +package main + +import ( + "context" + "crypto/sha256" + "fmt" + "net/http" + "os" + "sync" + "sync/atomic" + "time" + + traefikllmgateway "github.com/lukaszraczylo/traefik-llmgateway" +) + +// genRetired is the retired flag in a generation's state word. The bits below it count the requests running on it. +// The flag and the count share one atomic so that leave sees both in one operation (formal/Gateway/Reload.lean). +const genRetired int64 = 1 << 62 + +// generation is one constructed gateway and the requests running on it. +type generation struct { + h http.Handler + closeFn func() + timer atomic.Pointer[time.Timer] + state atomic.Int64 + once sync.Once + shutDone atomic.Bool +} + +func newGeneration(h http.Handler, closeFn func()) *generation { + return &generation{h: h, closeFn: closeFn} +} + +// enter counts a request in. It returns false when the generation is retired; the caller must not serve on it. +func (g *generation) enter() bool { + if g.state.Add(1)&genRetired != 0 { + g.leave() + return false + } + return true +} + +func (g *generation) leave() { + if g.state.Add(-1) == genRetired { + g.shut() + } +} + +// retire stops new requests. The gateway closes when the last running request leaves, or after maxWait. +func (g *generation) retire(maxWait time.Duration) { + if !g.markRetired() { + return + } + g.timer.Store(time.AfterFunc(maxWait, g.shut)) + // A shut that ran before the Store could not stop the timer, so stop it here. + if g.shutDone.Load() { + g.stopTimer() + } +} + +// markRetired sets the retired flag. It returns true when requests are still running, so the close waits for them. +// It closes an idle generation at once, and returns false when the generation was already retired. +func (g *generation) markRetired() bool { + for { + old := g.state.Load() + if old&genRetired != 0 { + return false + } + if g.state.CompareAndSwap(old, old|genRetired) { + if old == 0 { + g.shut() + return false + } + return true + } + } +} + +// shut closes the gateway once and stops the drain timer, so a closed generation is not held until it fires. +func (g *generation) shut() { + g.once.Do(func() { + g.closeFn() + g.shutDone.Store(true) + g.stopTimer() + }) +} + +func (g *generation) stopTimer() { + if t := g.timer.Load(); t != nil { + t.Stop() + } +} + +// swapHandler serves every request on the current generation. +type swapHandler struct { + cur atomic.Pointer[generation] +} + +func (s *swapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + for { + g := s.cur.Load() + // A false enter means a swap already installed a newer generation, so the next load finds it. + if g.enter() { + defer g.leave() + g.h.ServeHTTP(w, r) + return + } + } +} + +// swap installs next and retires the generation it replaces. +func (s *swapHandler) swap(next *generation, drain time.Duration) { + s.cur.Swap(next).retire(drain) +} + +// closeCurrent closes the serving generation and turns away any request that arrives later. +// Call it only after the server stopped serving. +func (s *swapHandler) closeCurrent() { + if g := s.cur.Load(); g != nil { + g.markRetired() + g.shut() + } +} + +// gatewayBuilder decodes raw as the config at path and constructs a gateway from it. +func gatewayBuilder(ctx context.Context, path, name string, log *logger) func(raw []byte) (http.Handler, error) { + return func(raw []byte) (http.Handler, error) { + cfg, err := decodeConfig(path, raw) + if err != nil { + return nil, err + } + logConfigWarnings(cfg, log) + h, err := traefikllmgateway.New(ctx, terminalHandler(), cfg, name) + if err != nil { + return nil, fmt.Errorf("construct gateway: %w", err) + } + return h, nil + } +} + +// reloader rebuilds the gateway when the config file content changes. Only its run goroutine calls check. +type reloader struct { + build func(raw []byte) (http.Handler, error) + swap *swapHandler + log *logger + path string + readErr string + buildErr string + drain time.Duration + last [sha256.Size]byte +} + +// newReloader starts from the content the serving gateway was built from. +func newReloader(path string, raw []byte, build func([]byte) (http.Handler, error), swap *swapHandler, drain time.Duration, log *logger) *reloader { + return &reloader{build: build, swap: swap, log: log, path: path, drain: drain, last: sha256.Sum256(raw)} +} + +// check rebuilds when the file content differs from the serving config, or always when force is set. +// A rejected config keeps the old gateway serving. It is retried on every check, because the cause can be outside +// the file (a secret file not mounted yet); each distinct error is logged once. +func (r *reloader) check(force bool) { + raw, err := os.ReadFile(r.path) + if err != nil { + r.readErr = r.logOnce(r.readErr, fmt.Sprintf("reload: read %s: %v; still serving the previous config", r.path, err)) + return + } + r.readErr = "" + sum := sha256.Sum256(raw) + if sum == r.last && !force { + return + } + h, err := r.build(raw) + if err != nil { + r.buildErr = r.logOnce(r.buildErr, fmt.Sprintf("reload: config %s rejected; still serving the previous config: %v", r.path, err)) + return + } + r.buildErr = "" + r.last = sum + r.swap.swap(newGeneration(h, func() { closeGateway(h, r.log) }), r.drain) + r.log.info("reload: config %s applied", r.path) +} + +// logOnce logs msg unless it equals prev, and returns msg as the new previous error. +func (r *reloader) logOnce(prev, msg string) string { + if msg != prev { + r.log.error("%s", msg) + } + return msg +} + +// run checks the file every interval (never when interval is 0) and on every value from hup, until ctx ends. +func (r *reloader) run(ctx context.Context, interval time.Duration, hup <-chan os.Signal) { + var tick <-chan time.Time + if interval > 0 { + t := time.NewTicker(interval) + defer t.Stop() + tick = t.C + } + for { + select { + case <-ctx.Done(): + return + case <-tick: + // select picks at random when ctx and tick are both ready; do not build after a shutdown signal. + if ctx.Err() != nil { + return + } + r.check(false) + case <-hup: + r.log.info("reload: SIGHUP, rebuilding from %s", r.path) + r.check(true) + } + } +} diff --git a/cmd/gateway/reload_test.go b/cmd/gateway/reload_test.go new file mode 100644 index 0000000..ac752f6 --- /dev/null +++ b/cmd/gateway/reload_test.go @@ -0,0 +1,374 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + traefikllmgateway "github.com/lukaszraczylo/traefik-llmgateway" +) + +// countingGen returns a generation over h whose close increments *closes. +func countingGen(h http.Handler, closes *atomic.Int32) *generation { + return newGeneration(h, func() { closes.Add(1) }) +} + +func okHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) +} + +func TestGenerationLifecycle(t *testing.T) { + tests := []struct { + run func(g *generation) + name string + wantCloses int32 + }{ + {name: "idle retire closes at once", run: func(g *generation) { g.retire(time.Hour) }, wantCloses: 1}, + {name: "retire waits for the running request", run: func(g *generation) { + g.enter() + g.retire(time.Hour) + }, wantCloses: 0}, + {name: "last leave closes a retired generation", run: func(g *generation) { + g.enter() + g.enter() + g.retire(time.Hour) + g.leave() + g.leave() + }, wantCloses: 1}, + {name: "leave on a live generation keeps it open", run: func(g *generation) { + g.enter() + g.leave() + }, wantCloses: 0}, + {name: "enter after retire is refused and closes nothing twice", run: func(g *generation) { + g.retire(time.Hour) + if g.enter() { + t.Error("enter on a retired generation must return false") + } + }, wantCloses: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var closes atomic.Int32 + g := countingGen(okHandler(), &closes) + tt.run(g) + if got := closes.Load(); got != tt.wantCloses { + t.Errorf("closes = %d, want %d", got, tt.wantCloses) + } + }) + } +} + +func TestGenerationDrainTimeoutForcesClose(t *testing.T) { + var closes atomic.Int32 + g := countingGen(okHandler(), &closes) + g.enter() + g.retire(20 * time.Millisecond) + deadline := time.Now().Add(2 * time.Second) + for closes.Load() == 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if closes.Load() != 1 { + t.Fatalf("closes = %d after the drain timeout, want 1", closes.Load()) + } + g.leave() + if closes.Load() != 1 { + t.Errorf("a leave after the forced close closed again: %d", closes.Load()) + } +} + +// TestSwapHandlerKeepsLongRequestOnOldGeneration: a request that started +// before a swap finishes on its own gateway, new requests reach the new +// one, and the old gateway closes only when the long request ends. +func TestSwapHandlerKeepsLongRequestOnOldGeneration(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}) + oldH := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + close(started) + <-release + w.Header().Set("X-Gen", "old") + }) + newH := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("X-Gen", "new") }) + + var oldCloses, newCloses atomic.Int32 + sw := &swapHandler{} + sw.cur.Store(countingGen(oldH, &oldCloses)) + + longRec := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + sw.ServeHTTP(longRec, httptest.NewRequest(http.MethodGet, "/", nil)) + close(done) + }() + <-started + + sw.swap(countingGen(newH, &newCloses), time.Hour) + + rec := httptest.NewRecorder() + sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + if got := rec.Header().Get("X-Gen"); got != "new" { + t.Errorf("request after swap served by %q, want new", got) + } + if oldCloses.Load() != 0 { + t.Fatal("old gateway closed while its request was still running") + } + close(release) + <-done + if got := longRec.Header().Get("X-Gen"); got != "old" { + t.Errorf("long request served by %q, want old", got) + } + if oldCloses.Load() != 1 || newCloses.Load() != 0 { + t.Errorf("closes old=%d new=%d, want 1 and 0", oldCloses.Load(), newCloses.Load()) + } +} + +// TestSwapHandlerNeverServesOnClosedGeneration races requests against +// swaps under -race. Each handler fails the test if its own gateway is +// already closed when it runs: that is the invariant formal/Gateway/Reload.lean +// proves for the packed state word. +func TestSwapHandlerNeverServesOnClosedGeneration(t *testing.T) { + sw := &swapHandler{} + var bad atomic.Int32 + mk := func() *generation { + var closed atomic.Bool + h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if closed.Load() { + bad.Add(1) + } + w.WriteHeader(http.StatusNoContent) + }) + return newGeneration(h, func() { closed.Store(true) }) + } + sw.cur.Store(mk()) + + var wg sync.WaitGroup + stop := make(chan struct{}) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + sw.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + } + }() + } + for i := 0; i < 300; i++ { + sw.swap(mk(), time.Hour) + } + close(stop) + wg.Wait() + if n := bad.Load(); n != 0 { + t.Fatalf("%d requests ran on a closed generation", n) + } +} + +func TestCloseCurrentTurnsAwayLaterRequests(t *testing.T) { + var closes atomic.Int32 + sw := &swapHandler{} + g := countingGen(okHandler(), &closes) + sw.cur.Store(g) + sw.closeCurrent() + if closes.Load() != 1 { + t.Fatalf("closes = %d, want 1", closes.Load()) + } + if g.enter() { + t.Error("enter after closeCurrent must return false") + } +} + +func TestShutStopsDrainTimer(t *testing.T) { + var closes atomic.Int32 + g := countingGen(okHandler(), &closes) + g.enter() + g.retire(time.Hour) + g.leave() + tm := g.timer.Load() + if tm == nil { + t.Fatal("retire with a running request set no drain timer") + } + if tm.Stop() { + t.Error("drain timer still pending after the generation closed") + } +} + +func TestParseOptionsReloadBounds(t *testing.T) { + tests := []struct { + name string + args []string + wantErr bool + }{ + {"defaults", nil, false}, + {"polling off", []string{"-reload-interval", "0"}, false}, + {"negative interval", []string{"-reload-interval", "-1s"}, true}, + {"zero drain", []string{"-reload-drain-timeout", "0"}, true}, + {"negative drain", []string{"-reload-drain-timeout", "-1s"}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := parseOptions(tt.args, os.Stderr) + if (err != nil) != tt.wantErr { + t.Errorf("err = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// fakeBuild records each build and fails when the file holds "bad". +type fakeBuild struct { + calls atomic.Int32 +} + +func (f *fakeBuild) build(raw []byte) (http.Handler, error) { + f.calls.Add(1) + if strings.Contains(string(raw), "bad") { + return nil, errors.New("rejected") + } + body := string(raw) + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(body)) }), nil +} + +func serveBody(t *testing.T, h http.Handler) string { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + return rec.Body.String() +} + +func TestReloaderAppliesOnlyChangedValidConfig(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + write := func(s string) { + t.Helper() + if err := os.WriteFile(path, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + write("one") + fb := &fakeBuild{} + h0, _ := fb.build([]byte("one")) + sw := &swapHandler{} + sw.cur.Store(newGeneration(h0, func() {})) + r := newReloader(path, []byte("one"), fb.build, sw, time.Hour, newLogger("error")) + fb.calls.Store(0) + + steps := []struct { + name string + content string + wantBody string + wantCalls int32 + force bool + }{ + {"same content does not rebuild", "one", "one", 0, false}, + {"changed content applies", "two", "two", 1, false}, + {"rejected config keeps the old gateway", "bad", "two", 2, false}, + {"rejected content is retried on the next check", "bad", "two", 3, false}, + {"a fixed file applies", "three", "three", 4, false}, + {"applied content is not rebuilt again", "three", "three", 4, false}, + {"force rebuilds unchanged content", "three", "three", 5, true}, + } + for _, s := range steps { + write(s.content) + r.check(s.force) + if got := serveBody(t, sw); got != s.wantBody { + t.Errorf("%s: served %q, want %q", s.name, got, s.wantBody) + } + if got := fb.calls.Load(); got != s.wantCalls { + t.Errorf("%s: builds = %d, want %d", s.name, got, s.wantCalls) + } + } +} + +func TestReloaderMissingFileKeepsServing(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + fb := &fakeBuild{} + h0, _ := fb.build([]byte("one")) + sw := &swapHandler{} + sw.cur.Store(newGeneration(h0, func() {})) + r := newReloader(path, []byte("one"), fb.build, sw, time.Hour, newLogger("error")) + r.check(false) + if got := serveBody(t, sw); got != "one" { + t.Errorf("served %q after the file vanished, want one", got) + } +} + +// TestReloadRealGateway reloads a real gateway from a config file and +// checks that the model list follows the file. +func TestReloadRealGateway(t *testing.T) { + const tmpl = `providers: + openai: + type: openai + apiKey: test-key + models: + - %s +groups: + default: + providers: [] +users: + inline: + - name: tester + group: default + apiKey: test-user-key +` + path := filepath.Join(t.TempDir(), "config.yaml") + cfgFor := func(model string) []byte { return []byte(strings.Replace(tmpl, "%s", model, 1)) } + if err := os.WriteFile(path, cfgFor("model-a"), 0o600); err != nil { + t.Fatal(err) + } + log := newLogger("error") + build := gatewayBuilder(context.Background(), path, "test", log) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + h, err := build(raw) + if err != nil { + t.Fatalf("build: %v", err) + } + sw := &swapHandler{} + sw.cur.Store(newGeneration(h, func() { closeGateway(h, log) })) + r := newReloader(path, raw, build, sw, time.Hour, log) + t.Cleanup(sw.closeCurrent) + + models := func() string { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) + req.Header.Set("Authorization", "Bearer test-user-key") + sw.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("/v1/models = %d: %s", rec.Code, rec.Body.String()) + } + return rec.Body.String() + } + if body := models(); !strings.Contains(body, "model-a") { + t.Fatalf("initial models lack model-a: %s", body) + } + if err := os.WriteFile(path, cfgFor("model-b"), 0o600); err != nil { + t.Fatal(err) + } + r.check(false) + body := models() + if !strings.Contains(body, "model-b") || strings.Contains(body, "model-a") { + t.Fatalf("models after reload = %s, want model-b only", body) + } +} + +// TestGatewayBuilderRejectsUnknownField keeps the strict decode on reload. +func TestGatewayBuilderRejectsUnknownField(t *testing.T) { + build := gatewayBuilder(context.Background(), "config.yaml", "test", newLogger("error")) + if _, err := build([]byte("providers: {}\nnotAField: 1\n")); err == nil { + t.Fatal("unknown field accepted on reload") + } +} + +var _ http.Handler = (*traefikllmgateway.Gateway)(nil)