Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
13 changes: 13 additions & 0 deletions changelog/unreleased/runtime-efficiency.md
Original file line number Diff line number Diff line change
@@ -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 份,避免异常日志把宿主机磁盘写满。
19 changes: 17 additions & 2 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
}
}
6 changes: 6 additions & 0 deletions deploy/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 4 additions & 3 deletions deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,16 +186,17 @@ 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 |
| `POST` | `/v1/responses` | OpenAI Responses-compatible API |
| `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
Expand Down
11 changes: 11 additions & 0 deletions deploy/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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:
7 changes: 7 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
110 changes: 110 additions & 0 deletions internal/auth/cache.go
Original file line number Diff line number Diff line change
@@ -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()
}
110 changes: 110 additions & 0 deletions internal/auth/cache_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading