diff --git a/.env.example b/.env.example index 7d9f46ccc..dd1091a1e 100644 --- a/.env.example +++ b/.env.example @@ -19,3 +19,9 @@ QODER_WORKER_BASE_PORT=32100 # UPDATE_AGENT_URL=http://host.docker.internal:3011 # UPDATE_AGENT_TOKEN= # UPDATE_GITHUB_TOKEN= + +# Positive API-key lookup cache in milliseconds. 0 disables it; values above +# 300000 are clamped. Console key edits invalidate the cache immediately. +# CLI2API_AUTH_CACHE_MS=30000 +# A streaming upstream that sends no bytes for this long is failed over. +# CLI2API_STREAM_IDLE_MS=300000 diff --git a/changelog/unreleased/runtime-efficiency.md b/changelog/unreleased/runtime-efficiency.md new file mode 100644 index 000000000..83e9e2c32 --- /dev/null +++ b/changelog/unreleased/runtime-efficiency.md @@ -0,0 +1,13 @@ +### English + +- API-key lookups are cached for 30 seconds (configurable with `CLI2API_AUTH_CACHE_MS`, `0` disables); console key edits and deletions invalidate the cache immediately, and `last_used_at` is written at most once per minute instead of on every request. +- Upstream HTTP keeps a 100-connection-per-host idle pool and bounds the response-head wait at five minutes, so bursts reuse TLS connections and a silent upstream fails over instead of pinning a request forever. +- Shutdown now drains: `/ready` reports 503 and new work is rejected while active streams finish for up to 30 seconds; compose waits 40 seconds before SIGKILL, and `/health` exposes the draining state. +- Compose caps container logs at 10 MB × 3 files so a chatty or failing gateway cannot fill the host disk. + +### 中文 + +- API Key 查询缓存 30 秒(可用 `CLI2API_AUTH_CACHE_MS` 调整,`0` 关闭);控制台修改或删除 Key 会立即失效缓存,`last_used_at` 最多每分钟写一次,不再每请求写一次 SQLite。 +- 上游 HTTP 连接池提升到每主机 100 个空闲连接,并把响应头等待上限设为 5 分钟;突发流量复用 TLS 连接,静默上游会触发切换而不是永久占住请求。 +- 关闭服务时先进入 draining:`/ready` 返回 503、新请求被拒绝,已有流最多 30 秒完成;compose 等待 40 秒再发 SIGKILL,`/health` 同时暴露 draining 状态。 +- compose 限制容器日志为 10 MB × 3 份,避免异常日志把宿主机磁盘写满。 diff --git a/cmd/server/main.go b/cmd/server/main.go index 4081199c9..5ffdb6464 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -12,11 +12,15 @@ import ( "github.com/caigee-cmd/cli2api/internal/app" "github.com/caigee-cmd/cli2api/internal/config" + "github.com/caigee-cmd/cli2api/internal/netx" "github.com/joho/godotenv" ) func main() { _ = godotenv.Load() + // Provider clients that leave Transport nil share this process-wide pool. + // Install the tuned transport before app.New constructs any client. + http.DefaultTransport = netx.Transport() cfg, err := config.Load() if err != nil { log.Fatal(err) @@ -40,9 +44,20 @@ func main() { } }() <-ctx.Done() - shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + // Stop reporting ready and reject new work before waiting for active + // requests. Existing streams keep their slots; the listener closes when + // Shutdown starts, and the middleware returns 503 to anything that still + // reaches it through a keep-alive connection. + if application.HTTP != nil { + application.HTTP.SetDraining(true) + } + const shutdownGrace = 30 * time.Second + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownGrace) defer cancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { - log.Printf("http shutdown failed: %v", err) + log.Printf("http shutdown did not finish within %s: %v", shutdownGrace, err) + // Force-close the remaining connections so the process exits cleanly + // instead of leaving handlers and their upstream streams running. + _ = httpServer.Close() } } diff --git a/deploy/.env.example b/deploy/.env.example index 1614ecdaa..a7fd27796 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -11,3 +11,9 @@ # UPDATE_AGENT_TOKEN= # Linux socket directory, or a harmless Docker Desktop placeholder directory. # CLI2API_UPDATER_SOCKET_DIR=/run/cli2api-updater + +# Positive API-key lookup cache in milliseconds (0 disables; max 300000). +# Console key edits invalidate immediately. +# CLI2API_AUTH_CACHE_MS=30000 +# Stream idle deadline before an upstream is considered dead. +# CLI2API_STREAM_IDLE_MS=300000 diff --git a/deploy/README.md b/deploy/README.md index 0147d0c35..368c524b9 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -186,7 +186,8 @@ not prompts, responses, tool arguments, or credentials. | Method | Path | Purpose | |--------|------|---------| -| `GET` | `/health` | Health probe; no API key required | +| `GET` | `/health` | Liveness probe; no API key required | +| `GET` | `/ready` | Readiness probe; 503 while draining or updating | | `GET` | `/v1/models` | Model catalog | | `POST` | `/v1/chat/completions` | OpenAI-compatible chat | | `POST` | `/v1/messages` | Anthropic-compatible messages | @@ -194,8 +195,8 @@ not prompts, responses, tool arguments, or credentials. | `GET/POST/PATCH/DELETE` | `/api/*` | Console management API | Console `/api/*` requires the administrator key. `/v1/*` accepts that key or an -enabled client key. `/health`, static frontend resources, and `/v1/*` CORS -preflight `OPTIONS` do not require authentication. +enabled client key. `/health`, `/ready`, static frontend resources, and `/v1/*` +CORS preflight `OPTIONS` do not require authentication. Messages / Responses are stateless compatibility APIs, not full official API implementations. They do not store server-side conversations or execute diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 9e7e91d99..e0ce33913 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -25,6 +25,9 @@ services: # per-request detail by default: the aggregates are ~200 bytes a row and # cannot be reconstructed once deleted. CLI2API_LOG_TOTALS_RETENTION_DAYS: "${CLI2API_LOG_TOTALS_RETENTION_DAYS:-730}" + # Positive API-key lookup cache. 0 disables it; max 300000 (5m). Console + # key changes invalidate immediately. + CLI2API_AUTH_CACHE_MS: "${CLI2API_AUTH_CACHE_MS:-30000}" volumes: - qoder-data:/data - "${CLI2API_UPDATER_SOCKET_DIR:-/tmp/cli2api-updater}:/run/cli2api-updater:ro" @@ -39,6 +42,14 @@ services: retries: 12 start_period: 30s restart: unless-stopped + # The server marks itself unready, rejects new work and gives active + # streams 30s to finish. Docker's default 10s SIGKILL would cut them. + stop_grace_period: 40s + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" volumes: qoder-data: diff --git a/internal/app/app.go b/internal/app/app.go index 478911d2e..dc64ee760 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -59,6 +59,7 @@ type App struct { stopLogsOnce sync.Once SettingsMu sync.Mutex CrossProviderModelPool atomic.Bool + Draining atomic.Bool Gateway *apigateway.Handler Console *appconsole.Handler Update *appupdate.Coordinator @@ -189,6 +190,11 @@ func New(cfg config.Config) *App { stopLogs: stopLogs, } a.CrossProviderModelPool.Store(crossProviderModelPool) + if a.Control != nil && a.Control.Keys != nil { + // A console key change must invalidate the auth cache immediately, not + // after the cache TTL. + a.Control.Keys.SetInvalidator(a.Auth.InvalidateKeyCache) + } a.Control.Catalog = appsvc.NewCatalog(a.FetchWorkerModelsForMode) a.Control.Catalog.Store = a.Manager.Store() a.Control.Catalog.Interval = cfg.CatalogRefreshInterval @@ -273,6 +279,7 @@ func (a *App) newHTTP() *httpserver.Server { Console: a.Console, Update: a.Update, CrossProvider: &a.CrossProviderModelPool, + Draining: &a.Draining, TouchKey: func(ctx context.Context, keyID string) { if a.Control != nil && a.Control.Keys != nil { _ = a.Control.Keys.Touch(ctx, keyID) diff --git a/internal/auth/cache.go b/internal/auth/cache.go new file mode 100644 index 000000000..5dbfb64d6 --- /dev/null +++ b/internal/auth/cache.go @@ -0,0 +1,110 @@ +package auth + +import ( + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +// Positive API-key lookups are cached briefly. Every public request otherwise +// costs one indexed SQLite read on a single-connection store, and a busy +// gateway fans out thousands of requests that all hit the same handful of keys. +// Console key changes invalidate the cache through control.Keys, so a disabled +// or deleted key stops working immediately; the TTL only bounds staleness for +// changes made directly in the database. +const ( + defaultKeyCacheTTL = 30 * time.Second + maxKeyCacheTTL = 5 * time.Minute + maxKeyCacheEntries = 1024 + keyCacheTTLEnv = "CLI2API_AUTH_CACHE_MS" +) + +func resolveKeyCacheTTL() time.Duration { + raw := strings.TrimSpace(os.Getenv(keyCacheTTLEnv)) + if raw == "" { + return defaultKeyCacheTTL + } + ms, err := strconv.Atoi(raw) + if err != nil { + return defaultKeyCacheTTL + } + if ms <= 0 { + return 0 + } + ttl := time.Duration(ms) * time.Millisecond + if ttl > maxKeyCacheTTL { + return maxKeyCacheTTL + } + return ttl +} + +type cachedKey struct { + key accounts.APIKey + expiresAt time.Time +} + +type keyCache struct { + mu sync.Mutex + entries map[string]cachedKey + ttl time.Duration +} + +func newKeyCache(ttl time.Duration) *keyCache { + if ttl <= 0 { + return nil + } + return &keyCache{entries: make(map[string]cachedKey), ttl: ttl} +} + +func (c *keyCache) get(hash string, now time.Time) (accounts.APIKey, bool) { + if c == nil { + return accounts.APIKey{}, false + } + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[hash] + if !ok { + return accounts.APIKey{}, false + } + if now.After(entry.expiresAt) { + delete(c.entries, hash) + return accounts.APIKey{}, false + } + return entry.key, true +} + +func (c *keyCache) put(hash string, key accounts.APIKey, now time.Time) { + if c == nil || hash == "" { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if len(c.entries) >= maxKeyCacheEntries { + for candidate, entry := range c.entries { + if now.After(entry.expiresAt) { + delete(c.entries, candidate) + } + } + // A personal gateway has a handful of keys; if every slot is still live + // the cache is being abused, so reset rather than grow without bound. + if len(c.entries) >= maxKeyCacheEntries { + clear(c.entries) + } + } + c.entries[hash] = cachedKey{key: key, expiresAt: now.Add(c.ttl)} +} + +// invalidate drops every cached key. It is called after a console key change +// so revocation never waits for a TTL. +func (c *keyCache) invalidate() { + if c == nil { + return + } + c.mu.Lock() + clear(c.entries) + c.mu.Unlock() +} diff --git a/internal/auth/cache_test.go b/internal/auth/cache_test.go new file mode 100644 index 000000000..818119472 --- /dev/null +++ b/internal/auth/cache_test.go @@ -0,0 +1,110 @@ +package auth + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +type countingKeys struct { + calls atomic.Int32 + key accounts.APIKey + ok bool +} + +func (c *countingKeys) LookupAPIKey(_ context.Context, secret string) (accounts.APIKey, bool, error) { + c.calls.Add(1) + if secret != "named-secret" { + return accounts.APIKey{}, false, nil + } + return c.key, c.ok, nil +} + +func keyRequest() *http.Request { + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + req.Header.Set("Authorization", "Bearer named-secret") + return req +} + +func TestVerifierCachesPositiveLookupUntilInvalidated(t *testing.T) { + t.Setenv(keyCacheTTLEnv, "30000") + lookup := &countingKeys{ + ok: true, + key: accounts.APIKey{ID: "key_1", Name: "ci", Enabled: true, Providers: []string{"qoder"}}, + } + verifier := NewVerifier("console", lookup) + + for i := 0; i < 3; i++ { + if _, ok := verifier.Authenticate(context.Background(), keyRequest()); !ok { + t.Fatal("cached key was rejected") + } + } + if got := lookup.calls.Load(); got != 1 { + t.Fatalf("lookup calls = %d, want 1", got) + } + + verifier.InvalidateKeyCache() + if _, ok := verifier.Authenticate(context.Background(), keyRequest()); !ok { + t.Fatal("key was rejected after invalidation") + } + if got := lookup.calls.Load(); got != 2 { + t.Fatalf("lookup calls after invalidation = %d, want 2", got) + } +} + +func TestVerifierDoesNotCacheDisabledKey(t *testing.T) { + t.Setenv(keyCacheTTLEnv, "30000") + lookup := &countingKeys{ + ok: true, + key: accounts.APIKey{ID: "key_1", Name: "ci", Enabled: false}, + } + verifier := NewVerifier("console", lookup) + for i := 0; i < 2; i++ { + if _, ok := verifier.Authenticate(context.Background(), keyRequest()); ok { + t.Fatal("disabled key was accepted") + } + } + if got := lookup.calls.Load(); got != 2 { + t.Fatalf("lookup calls = %d, want 2 (disabled keys must not be cached)", got) + } +} + +func TestVerifierCacheExpires(t *testing.T) { + lookup := &countingKeys{ + ok: true, + key: accounts.APIKey{ID: "key_1", Name: "ci", Enabled: true}, + } + verifier := NewVerifier("console", lookup) + verifier.cache = newKeyCache(2 * time.Millisecond) + + if _, ok := verifier.Authenticate(context.Background(), keyRequest()); !ok { + t.Fatal("key was rejected") + } + time.Sleep(5 * time.Millisecond) + if _, ok := verifier.Authenticate(context.Background(), keyRequest()); !ok { + t.Fatal("key was rejected after expiry") + } + if got := lookup.calls.Load(); got != 2 { + t.Fatalf("lookup calls = %d, want 2 after expiry", got) + } +} + +func TestVerifierCacheCanBeDisabled(t *testing.T) { + t.Setenv(keyCacheTTLEnv, "0") + lookup := &countingKeys{ + ok: true, + key: accounts.APIKey{ID: "key_1", Name: "ci", Enabled: true}, + } + verifier := NewVerifier("console", lookup) + for i := 0; i < 2; i++ { + verifier.Authenticate(context.Background(), keyRequest()) + } + if got := lookup.calls.Load(); got != 2 { + t.Fatalf("lookup calls = %d, want 2 when cache is disabled", got) + } +} diff --git a/internal/auth/verifier.go b/internal/auth/verifier.go index b20312949..e9d7471d2 100644 --- a/internal/auth/verifier.go +++ b/internal/auth/verifier.go @@ -5,6 +5,7 @@ import ( "net/http" "strings" "sync/atomic" + "time" "github.com/caigee-cmd/cli2api/internal/accounts" ) @@ -16,15 +17,23 @@ type KeyLookup interface { type Verifier struct { consoleKey *atomic.Pointer[string] keys KeyLookup + cache *keyCache } func NewVerifier(consoleKey string, keys KeyLookup) Verifier { key := &atomic.Pointer[string]{} - v := Verifier{consoleKey: key, keys: keys} + v := Verifier{consoleKey: key, keys: keys, cache: newKeyCache(resolveKeyCacheTTL())} v.SetConsoleKey(consoleKey) return v } +// InvalidateKeyCache drops cached API-key identities after a console key +// change. Copies of Verifier share the cache pointer, so this reaches every +// handler copy. +func (v Verifier) InvalidateKeyCache() { + v.cache.invalidate() +} + // ConsoleKey reads the shared live key. Copies of Verifier share this state. func (v Verifier) ConsoleKey() string { if v.consoleKey == nil { @@ -70,9 +79,15 @@ func (v Verifier) Authenticate(ctx context.Context, r *http.Request) (Identity, if v.keys == nil { return Identity{}, false } + hash := accounts.HashAPIKey(secret) + now := time.Now() + if key, ok := v.cache.get(hash, now); ok { + return KeyIdentity(key), true + } key, ok, err := v.keys.LookupAPIKey(ctx, secret) if err != nil || !ok || !key.Enabled { return Identity{}, false } + v.cache.put(hash, key, now) return KeyIdentity(key), true } diff --git a/internal/control/keys.go b/internal/control/keys.go index 618bece23..1a42051de 100644 --- a/internal/control/keys.go +++ b/internal/control/keys.go @@ -2,20 +2,44 @@ package control import ( "context" + "sync" "time" "github.com/caigee-cmd/cli2api/internal/accounts" ) +// touchWriteInterval bounds how often one key's last_used_at is written. The +// value is display metadata, not auth state: writing it on every request puts a +// synchronous SQLite UPDATE in front of every completion. +const touchWriteInterval = time.Minute + type Keys struct { store accounts.AccountStore + // invalidate drops the auth verifier's positive-key cache after a console + // mutation, so revocation does not wait for the cache TTL. + invalidate func() + touchMu sync.Mutex + touched map[string]time.Time } func NewKeys(store accounts.AccountStore) *Keys { if store == nil { return nil } - return &Keys{store: store} + return &Keys{store: store, touched: make(map[string]time.Time)} +} + +func (k *Keys) SetInvalidator(fn func()) { + if k == nil { + return + } + k.invalidate = fn +} + +func (k *Keys) changed() { + if k != nil && k.invalidate != nil { + k.invalidate() + } } func (k *Keys) List(ctx context.Context) ([]accounts.APIKey, error) { @@ -53,6 +77,7 @@ func (k *Keys) Create(ctx context.Context, input accounts.CreateAPIKey) (account if err != nil { return accounts.APIKey{}, err } + k.changed() stored.Secret = secret stored.SecretOnce = true return stored, nil @@ -71,7 +96,7 @@ func (k *Keys) Update(ctx context.Context, id string, input accounts.UpdateAPIKe if err != nil { return accounts.APIKey{}, err } - return k.store.SaveAPIKey(ctx, accounts.StoredAPIKey{ + saved, err := k.store.SaveAPIKey(ctx, accounts.StoredAPIKey{ ID: merged.ID, Name: merged.Name, Prefix: merged.Prefix, @@ -81,10 +106,22 @@ func (k *Keys) Update(ctx context.Context, id string, input accounts.UpdateAPIKe ModelAggregation: merged.ModelAggregation, UpdatedAt: time.Now().UTC(), }) + if err != nil { + return accounts.APIKey{}, err + } + k.changed() + return saved, nil } func (k *Keys) Delete(ctx context.Context, id string) error { - return k.store.DeleteAPIKey(ctx, id) + if err := k.store.DeleteAPIKey(ctx, id); err != nil { + return err + } + k.touchMu.Lock() + delete(k.touched, id) + k.touchMu.Unlock() + k.changed() + return nil } func (k *Keys) SetConsoleSecret(ctx context.Context, secretName, secret string) error { @@ -92,5 +129,21 @@ func (k *Keys) SetConsoleSecret(ctx context.Context, secretName, secret string) } func (k *Keys) Touch(ctx context.Context, id string) error { - return k.store.TouchAPIKey(ctx, id) + now := time.Now() + k.touchMu.Lock() + if last, ok := k.touched[id]; ok && now.Sub(last) < touchWriteInterval { + k.touchMu.Unlock() + return nil + } + k.touched[id] = now + k.touchMu.Unlock() + + if err := k.store.TouchAPIKey(ctx, id); err != nil { + // A failed write must not suppress the next attempt for a full interval. + k.touchMu.Lock() + delete(k.touched, id) + k.touchMu.Unlock() + return err + } + return nil } diff --git a/internal/control/s06_control_test.go b/internal/control/s06_control_test.go index f05276187..e610d07b5 100644 --- a/internal/control/s06_control_test.go +++ b/internal/control/s06_control_test.go @@ -635,6 +635,52 @@ func TestKeysUpdateKeepsOriginalSecret(t *testing.T) { } } +func TestKeysTouchDebouncesRepeatedWrites(t *testing.T) { + log := &callLog{} + keys := NewKeys(newFakeStore(log)) + created, err := keys.Create(context.Background(), accounts.CreateAPIKey{Name: "CI", Enabled: true}) + if err != nil { + t.Fatalf("create: %v", err) + } + touches := func() int { + count := 0 + for _, name := range log.names { + if name == "store.TouchAPIKey" { + count++ + } + } + return count + } + for i := 0; i < 3; i++ { + if err := keys.Touch(context.Background(), created.ID); err != nil { + t.Fatalf("touch: %v", err) + } + } + if got := touches(); got != 1 { + t.Fatalf("touch writes = %d, want 1 within the debounce interval", got) + } +} + +func TestKeysMutationInvalidatesAuthCache(t *testing.T) { + keys := NewKeys(newFakeStore(&callLog{})) + invalidations := 0 + keys.SetInvalidator(func() { invalidations++ }) + + created, err := keys.Create(context.Background(), accounts.CreateAPIKey{Name: "CI", Enabled: true}) + if err != nil { + t.Fatalf("create: %v", err) + } + if invalidations != 1 { + t.Fatalf("invalidations after create = %d, want 1", invalidations) + } + if err := keys.Delete(context.Background(), created.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if invalidations != 2 { + t.Fatalf("invalidations after delete = %d, want 2", invalidations) + } +} + func equalCalls(got, want []string) bool { if len(got) != len(want) { return false diff --git a/internal/endpoint/routes.go b/internal/endpoint/routes.go index dd39eb7f5..795e0dcfa 100644 --- a/internal/endpoint/routes.go +++ b/internal/endpoint/routes.go @@ -2,6 +2,7 @@ package endpoint const ( HealthPath = "/health" + ReadyPath = "/ready" ModelsPath = "/v1/models" ChatCompletionsPath = "/v1/chat/completions" MessagesPath = "/v1/messages" diff --git a/internal/executor/chat.go b/internal/executor/chat.go index 11116216e..e9f49f390 100644 --- a/internal/executor/chat.go +++ b/internal/executor/chat.go @@ -16,6 +16,7 @@ import ( "time" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/netx" "github.com/caigee-cmd/cli2api/internal/providers" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -307,7 +308,8 @@ func NewChatExecutor(pool *Pool, workerKey string) ChatExecutor { MaxAttempts: 4, SessionAffinity: NewSessionAffinity(defaultSessionAffinityTTL, defaultSessionAffinityCapacity), HTTPClient: &http.Client{ - Timeout: 120 * time.Second, + Timeout: 120 * time.Second, + Transport: netx.Transport(), }, } } diff --git a/internal/netx/transport.go b/internal/netx/transport.go new file mode 100644 index 000000000..2510c49ea --- /dev/null +++ b/internal/netx/transport.go @@ -0,0 +1,47 @@ +// Package netx owns the process-wide HTTP transport defaults. +// +// The gateway fans many concurrent requests out to a handful of upstream hosts. +// Go's default transport keeps only two idle connections per host, so a burst +// of streams closes and reopens TLS connections continuously. Every reconnect +// adds a handshake to the caller's first byte and burns CPU on both sides. The +// transport here keeps a wider idle pool and bounds the response-head wait, so +// an upstream that accepts a connection and never answers cannot pin a +// request goroutine forever. +package netx + +import ( + "net/http" + "time" +) + +const ( + maxIdleConns = 200 + maxIdleConnsPerHost = 100 + idleConnTimeout = 90 * time.Second + // responseHeaderTimeout mirrors the stream idle deadline. A non-streaming + // upstream may legitimately spend minutes generating before it sends headers, + // so this must stay generous; it exists to stop an indefinite hang, not to + // police normal latency. + responseHeaderTimeout = 5 * time.Minute +) + +// Transport returns a tuned clone of the standard transport. Callers must not +// mutate the returned value after handing it to a client. +func Transport() *http.Transport { + base, ok := http.DefaultTransport.(*http.Transport) + if !ok || base == nil { + base = &http.Transport{Proxy: http.ProxyFromEnvironment} + } else { + base = base.Clone() + } + base.MaxIdleConns = maxIdleConns + base.MaxIdleConnsPerHost = maxIdleConnsPerHost + // Zero means no per-host cap: streams are long-lived and a low cap would + // queue new requests behind established ones. + base.MaxConnsPerHost = 0 + base.IdleConnTimeout = idleConnTimeout + base.ResponseHeaderTimeout = responseHeaderTimeout + base.ExpectContinueTimeout = time.Second + base.ForceAttemptHTTP2 = true + return base +} diff --git a/internal/netx/transport_test.go b/internal/netx/transport_test.go new file mode 100644 index 000000000..6af53a93d --- /dev/null +++ b/internal/netx/transport_test.go @@ -0,0 +1,37 @@ +package netx + +import ( + "net/http" + "testing" + "time" +) + +func TestTransportKeepsWideIdlePoolAndBoundsHeaderWait(t *testing.T) { + transport := Transport() + if transport.MaxIdleConnsPerHost != 100 { + t.Fatalf("MaxIdleConnsPerHost = %d, want 100", transport.MaxIdleConnsPerHost) + } + if transport.MaxIdleConns < transport.MaxIdleConnsPerHost { + t.Fatalf("MaxIdleConns = %d smaller than per-host pool", transport.MaxIdleConns) + } + if transport.MaxConnsPerHost != 0 { + t.Fatalf("MaxConnsPerHost = %d, want unlimited", transport.MaxConnsPerHost) + } + if transport.ResponseHeaderTimeout != 5*time.Minute { + t.Fatalf("ResponseHeaderTimeout = %s, want 5m", transport.ResponseHeaderTimeout) + } + if !transport.ForceAttemptHTTP2 { + t.Fatal("HTTP/2 disabled") + } +} + +func TestTransportStartsFromDefaultSettings(t *testing.T) { + transport := Transport() + if transport.Proxy == nil { + t.Fatal("proxy function was not preserved") + } + // The standard transport is shared; the clone must not be the same object. + if transport == http.DefaultTransport.(*http.Transport) { + t.Fatal("Transport returned the shared default instead of a clone") + } +} diff --git a/internal/providers/codearts/client.go b/internal/providers/codearts/client.go index 4aa187631..1f5bbb122 100644 --- a/internal/providers/codearts/client.go +++ b/internal/providers/codearts/client.go @@ -12,6 +12,7 @@ import ( "time" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/netx" "github.com/caigee-cmd/cli2api/internal/providers" proxyutil "github.com/caigee-cmd/cli2api/internal/proxy" ) @@ -62,15 +63,10 @@ type Client struct { } func NewClient(store Store) *Client { - transport := &http.Transport{ - MaxIdleConns: 20, - MaxIdleConnsPerHost: 4, - IdleConnTimeout: 90 * time.Second, - } return &Client{ store: store, http: &http.Client{ - Transport: transport, + Transport: netx.Transport(), CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, diff --git a/internal/server/health.go b/internal/server/health.go index 766adb667..604727547 100644 --- a/internal/server/health.go +++ b/internal/server/health.go @@ -29,5 +29,25 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { "version": buildinfo.Version, "commit": buildinfo.Commit, "maintenance": s.updater().Maintenance.Load(), + "draining": s.draining(), + }) +} + +// handleReady separates liveness from readiness: Docker should keep the +// container alive while it drains, but a load balancer or orchestrator must +// stop sending new work as soon as the process starts shutting down. +func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) { + ready := !s.draining() && !s.updater().Maintenance.Load() + status := http.StatusOK + if !ready { + status = http.StatusServiceUnavailable + } + writeJSON(w, status, map[string]any{ + "ok": ready, + "draining": s.draining(), + "maintenance": s.updater().Maintenance.Load(), + "version": buildinfo.Version, + "commit": buildinfo.Commit, + "time": time.Now().UTC().Format(time.RFC3339), }) } diff --git a/internal/server/health_test.go b/internal/server/health_test.go new file mode 100644 index 000000000..8df73c214 --- /dev/null +++ b/internal/server/health_test.go @@ -0,0 +1,71 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +func TestReadyFollowsDrainingState(t *testing.T) { + var draining atomic.Bool + server := New(Server{Draining: &draining}) + + ready := func() (*httptest.ResponseRecorder, map[string]any) { + rec := httptest.NewRecorder() + server.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ready", nil)) + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode ready body: %v", err) + } + return rec, body + } + + rec, body := ready() + if rec.Code != http.StatusOK || body["ok"] != true { + t.Fatalf("ready before drain = %d %v", rec.Code, body) + } + + server.SetDraining(true) + rec, body = ready() + if rec.Code != http.StatusServiceUnavailable || body["ok"] != false || body["draining"] != true { + t.Fatalf("ready after drain = %d %v", rec.Code, body) + } + + health := httptest.NewRecorder() + server.Handler().ServeHTTP(health, httptest.NewRequest(http.MethodGet, "/health", nil)) + if health.Code != http.StatusOK { + t.Fatalf("health during drain = %d, want 200", health.Code) + } + var healthBody map[string]any + if err := json.Unmarshal(health.Body.Bytes(), &healthBody); err != nil { + t.Fatalf("decode health body: %v", err) + } + if healthBody["draining"] != true || healthBody["ok"] != true { + t.Fatalf("health during drain = %v", healthBody) + } +} + +func TestHandlerRejectsNewWorkWhileDraining(t *testing.T) { + var draining atomic.Bool + server := New(Server{Draining: &draining}) + server.SetDraining(true) + + rec := httptest.NewRecorder() + server.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/v1/models", nil)) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status while draining = %d, want 503", rec.Code) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode drain body: %v", err) + } + errObj, _ := body["error"].(map[string]any) + if errObj["code"] != "service_draining" { + t.Fatalf("drain error = %v", body["error"]) + } + if rec.Header().Get("Connection") != "close" { + t.Fatalf("Connection header = %q, want close", rec.Header().Get("Connection")) + } +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go index c57946b9d..d1173e57b 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -11,6 +11,11 @@ import ( func (s *Server) Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if s.draining() && !isLivenessPath(r.URL.Path) { + w.Header().Set("Connection", "close") + writeErr(w, http.StatusServiceUnavailable, "service_draining", "Service is shutting down") + return + } if isOpenAIEndpoint(r.URL.Path) { setOpenAICORSHeaders(w, r) if r.Method == http.MethodOptions { @@ -26,6 +31,12 @@ func (s *Server) Handler() http.Handler { }) } +// isLivenessPath keeps probes usable while the process drains; everything else +// is new work and gets a clean 503 instead of a connection reset. +func isLivenessPath(path string) bool { + return path == endpoint.HealthPath || path == endpoint.ReadyPath +} + func isOpenAIEndpoint(path string) bool { switch path { case endpoint.ModelsPath, endpoint.ChatCompletionsPath, endpoint.MessagesPath, endpoint.ResponsesPath: diff --git a/internal/server/router.go b/internal/server/router.go index 845541ba7..e5ab017f2 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -11,6 +11,7 @@ import ( func (s *Server) routes() { s.mux.HandleFunc(endpoint.HealthPath, s.handleHealth) s.mux.HandleFunc("/api/events", s.withConsoleKey(s.consoleHandler().HandleEvents)) + s.mux.HandleFunc(endpoint.ReadyPath, s.handleReady) s.mux.HandleFunc("/api/overview", s.withConsoleKey(s.consoleHandler().HandleOverview)) s.mux.HandleFunc("/api/overview/summary", s.withConsoleKey(s.consoleHandler().HandleOverviewSummary)) s.mux.HandleFunc("/api/live", s.withConsoleKey(s.consoleHandler().HandleLive)) diff --git a/internal/server/server.go b/internal/server/server.go index 139c3c79d..997c46c03 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -20,6 +20,9 @@ type Server struct { Update *appupdate.Coordinator TouchKey func(ctx context.Context, keyID string) CrossProvider *atomic.Bool + // Draining is set while the process is shutting down. Health stays 200 + // (the process is alive) but readiness and new work return 503. + Draining *atomic.Bool mux *http.ServeMux } @@ -58,3 +61,15 @@ func (s *Server) consoleHandler() *appconsole.Handler { func (s *Server) crossProviderOn() bool { return s != nil && s.CrossProvider != nil && s.CrossProvider.Load() } + +func (s *Server) draining() bool { + return s != nil && s.Draining != nil && s.Draining.Load() +} + +// SetDraining flips readiness and rejects new work. Safe on a nil server. +func (s *Server) SetDraining(on bool) { + if s == nil || s.Draining == nil { + return + } + s.Draining.Store(on) +}