claude-code-proxy/.env.example
sid 8e550b9785 Local fork: hardening + ops improvements (timeout knob, demotion, /livez, drain)
This commit captures both the prior accumulated work-in-progress
(framework migration web/→svelte/, postgres storage, conversation
viewer, dashboard auth, OpenAPI spec, integration tests) AND today's
operational improvements layered on top. History wasn't checkpointed
incrementally; happy to split it via interactive rebase if a reviewer
wants smaller commits.

Today's changes (in addition to the older WIP):

1. Configurable upstream response-header timeout
   - ANTHROPIC_RESPONSE_HEADER_TIMEOUT env (default 300s)
   - Replaces hardcoded 300s in provider/anthropic.go that was firing
     on opus + 1M-context + extended thinking non-streaming requests
   - Files: internal/config/config.go, internal/provider/anthropic.go

2. Structured forward-error diagnostic logging
   - When a forward to Anthropic fails, log a single key=value line
     with request_id, model, stream, body_bytes, has_thinking,
     anthropic_beta, query, elapsed, ctx_err — alongside the existing
     human-readable error line for back-compat
   - Files: internal/handler/handlers.go (logForwardFailure)

3. Full SSE protocol passthrough + Flusher fix
   - handler/handlers.go: forward all SSE lines verbatim (event:, id:,
     retry:, : comments, blank-line terminators), not only data:.
     Previous code produced malformed SSE for strict parsers.
   - middleware/logging.go: explicit Flush() method on responseWriter.
     Embedding http.ResponseWriter (interface) does not auto-promote
     Flush(), so every w.(http.Flusher) check in the streaming
     handler was returning ok=false and SSE writes buffered in net/http
     until the body closed.

4. Non-streaming → streaming demotion (feature-flagged)
   - ANTHROPIC_DEMOTE_NONSTREAMING env (default false)
   - When enabled and the routed provider is anthropic, force stream=true
     upstream for clients that asked for stream=false. Receive SSE,
     accumulate via accumulateSSEToMessage (handles text, tool_use with
     partial_json reassembly, thinking, signature, citations_delta,
     usage merge), and synthesize a single non-streaming JSON response.
   - Eliminates the ResponseHeaderTimeout class of failure entirely.
   - Body rewrite uses json.Decoder + UseNumber() to preserve integer
     precision in unknown nested fields (tool inputs from prior turns).
   - Files: internal/config/config.go, internal/handler/handlers.go,
     cmd/proxy/main.go, cmd/proxy/main_test.go

5. Live operational state: /livez gauge + graceful drain
   - New internal/runtime package: atomic in-flight counter + draining flag
   - New middleware/inflight.go: increments runtime gauge, applied to
     /v1/* subrouter so Messages, ChatCompletions, and ProxyPassthrough
     are all counted
   - /v1/* moved to a gorilla/mux subrouter so the InFlight middleware
     applies surgically; /health, /livez, /openapi.* remain on parent
     router (unauthenticated, uncounted)
   - Health handler returns 503 draining when runtime.IsDraining() is
     true, so Traefik stops routing to a slot before drain begins
   - New /livez handler returns {status, in_flight, draining, timestamp}
   - SIGTERM handler in main.go: SetDraining(true), poll for in_flight==0
     with 32-min ceiling and 1s tick (logs every 10s), then srv.Shutdown
   - Auth bypass list extended with /livez
   - Files: internal/runtime/runtime.go (new),
     internal/middleware/inflight.go (new),
     internal/middleware/auth.go,
     internal/handler/handlers.go (Health, Livez, runtime import),
     cmd/proxy/main.go (subrouter, drain loop)

6. OpenAPI spec updates
   - Document Health 503 response and new DrainingResponse schema
   - Add /livez path with LivezResponse schema
   - Files: internal/handler/openapi.go

Verified: go build ./... clean, go test ./... all pass, go vet clean.
Three rounds of codex peer review across changes 1-5; all feedback
addressed (citations_delta, json.Number precision, drain-loop logging
via lastLog timestamp, PathPrefix tightened to "/v1/").
2026-05-02 15:15:58 -06:00

57 lines
2.1 KiB
Text

# Claude Code Proxy Configuration
# Server Configuration
SERVER_HOST=127.0.0.1
PORT=3001
READ_TIMEOUT=500
WRITE_TIMEOUT=500
IDLE_TIMEOUT=500
# Anthropic API Configuration
# URL to forward requests to (the actual Anthropic API)
ANTHROPIC_FORWARD_URL=https://api.anthropic.com
ANTHROPIC_VERSION=2023-06-01
ANTHROPIC_MAX_RETRIES=3
# OpenAI Configuration (for subagent routing)
# OPENAI_API_KEY=your-openai-api-key
# OPENAI_BASE_URL=https://api.openai.com
# OPENAI_ALLOW_CLIENT_API_KEY=false
# OPENAI_CLIENT_API_KEY_HEADER=x-openai-api-key
# Auth Configuration
# AUTH_ENABLED=false
# AUTH_TOKEN=change-me
# AUTH_API_KEY_HEADER=x-api-key
# AUTH_ALLOW_LOCALHOST_BYPASS=true
# Dashboard Auth (protects web UI and data endpoints with HTTP basic auth)
# When set, accessing the dashboard or /api/* data routes requires user "admin"
# with this password. Proxy endpoints (/v1/messages, /health) are NOT affected.
# DASHBOARD_PASSWORD=change-me-to-a-strong-password
# Reverse-proxy deployments
# Set this to true when the proxy itself binds publicly but is only reachable
# through a trusted reverse proxy such as Traefik.
# TRUST_PROXY=true
# Storage Configuration
# DB_TYPE=sqlite
# DATABASE_URL=postgresql://user:password@localhost:5432/claude_code_proxy?sslmode=disable
# TEST_POSTGRES_DSN=postgresql://user:password@localhost:5432/claude_code_proxy_test?sslmode=disable
# TEST_POSTGRES_USER=test
# TEST_POSTGRES_PASSWORD=test
# TEST_POSTGRES_DB=claude_code_proxy_test
# TEST_POSTGRES_PORT=5434
DB_PATH=requests.db
STORAGE_CAPTURE_REQUEST_BODY=true
STORAGE_CAPTURE_RESPONSE_BODY=true
STORAGE_METADATA_ONLY=false
STORAGE_RETENTION_DAYS=0
# STORAGE_REDACTED_FIELDS=api_key,authorization,token,password,secret,access_token,refresh_token,client_secret
# CORS Configuration (comma-separated values)
# Defaults are permissive. Set these explicitly if you want tighter browser access.
# CORS_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000,http://localhost:5174,http://127.0.0.1:5174
# CORS_ALLOWED_METHODS=GET,POST,DELETE,OPTIONS
# CORS_ALLOWED_HEADERS=Accept,Authorization,Content-Type,Anthropic-Version,Anthropic-Beta,X-API-Key,X-Requested-With