claude-code-proxy/proxy/internal/handler/handlers_settings_test.go

210 lines
6.6 KiB
Go
Raw Normal View History

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
package handler
import (
"bytes"
"errors"
"io"
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/seifghazi/claude-code-monitor/internal/config"
"github.com/seifghazi/claude-code-monitor/internal/model"
)
type stubStorage struct {
getSettingsFn func() (*model.ProxySettings, error)
saveSettingsFn func(settings *model.ProxySettings) error
getCalls int
saveCalls int
}
func (s *stubStorage) SaveRequest(*model.RequestLog) (string, error) { panic("unexpected call") }
func (s *stubStorage) GetRequests(int, int, string) ([]model.RequestLog, int, error) {
panic("unexpected call")
}
func (s *stubStorage) GetAllRequests(string) ([]*model.RequestLog, error) { panic("unexpected call") }
func (s *stubStorage) GetRequestByShortID(string) (*model.RequestLog, string, error) {
panic("unexpected call")
}
func (s *stubStorage) ClearRequests() (int, error) { panic("unexpected call") }
func (s *stubStorage) UpdateRequestWithGrading(string, *model.PromptGrade) error {
panic("unexpected call")
}
func (s *stubStorage) UpdateRequestWithResponse(*model.RequestLog) error { panic("unexpected call") }
func (s *stubStorage) DeleteRequestsOlderThan(time.Duration) (int, error) { panic("unexpected call") }
func (s *stubStorage) GetDatabaseStats() (map[string]interface{}, error) { panic("unexpected call") }
func (s *stubStorage) GetUsageStats(string, string, string, string) (*model.UsageStats, error) {
panic("unexpected call")
}
func (s *stubStorage) GetRequestsSummary(string) ([]*model.RequestSummary, error) {
panic("unexpected call")
}
func (s *stubStorage) GetRequestsSummaryPaginated(string, string, string, int, int) ([]*model.RequestSummary, int, error) {
panic("unexpected call")
}
func (s *stubStorage) GetStats(string, string, string) (*model.DashboardStats, error) {
panic("unexpected call")
}
func (s *stubStorage) GetHourlyStats(string, string, int, string) (*model.HourlyStatsResponse, error) {
panic("unexpected call")
}
func (s *stubStorage) GetModelStats(string, string, string) (*model.ModelStatsResponse, error) {
panic("unexpected call")
}
func (s *stubStorage) GetLatestRequestDate() (*time.Time, error) { panic("unexpected call") }
func (s *stubStorage) GetDistinctOrganizations() ([]string, error) { panic("unexpected call") }
func (s *stubStorage) GetSettings() (*model.ProxySettings, error) {
s.getCalls++
if s.getSettingsFn != nil {
return s.getSettingsFn()
}
return &model.ProxySettings{}, nil
}
func (s *stubStorage) SaveSettings(settings *model.ProxySettings) error {
s.saveCalls++
if s.saveSettingsFn != nil {
return s.saveSettingsFn(settings)
}
return nil
}
func (s *stubStorage) GetConfig() *config.StorageConfig { return &config.StorageConfig{} }
func (s *stubStorage) EnsureDirectoryExists() error { return nil }
func (s *stubStorage) Close() error { return nil }
func TestGetCachedSettingsCachesFirstLoad(t *testing.T) {
storage := &stubStorage{
getSettingsFn: func() (*model.ProxySettings, error) {
return &model.ProxySettings{
RequestHeaderRules: []model.HeaderRule{{Header: "X-Test", Action: "set", Value: "1", Enabled: true}},
}, nil
},
}
h := &Handler{
storageService: storage,
logger: log.New(io.Discard, "", 0),
}
first := h.GetCachedSettings()
second := h.GetCachedSettings()
if storage.getCalls != 1 {
t.Fatalf("expected one storage read, got %d", storage.getCalls)
}
if len(first.RequestHeaderRules) != 1 || len(second.RequestHeaderRules) != 1 {
t.Fatalf("expected cached settings to be returned, got %#v %#v", first, second)
}
}
func TestSaveSettingsUpdatesCache(t *testing.T) {
storage := &stubStorage{}
h := &Handler{
storageService: storage,
logger: log.New(io.Discard, "", 0),
}
body := []byte(`{"requestHeaderRules":[{"header":"X-New","action":"set","value":"abc","enabled":true}]}`)
req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewReader(body))
rr := httptest.NewRecorder()
h.SaveSettings(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rr.Code)
}
if storage.saveCalls != 1 {
t.Fatalf("expected one settings save, got %d", storage.saveCalls)
}
cached := h.GetCachedSettings()
if storage.getCalls != 0 {
t.Fatalf("expected cached settings to avoid storage read, got %d reads", storage.getCalls)
}
if len(cached.RequestHeaderRules) != 1 || cached.RequestHeaderRules[0].Header != "X-New" {
t.Fatalf("expected cache updated from save, got %#v", cached)
}
}
func TestGetSettingsReturnsStorageError(t *testing.T) {
storage := &stubStorage{
getSettingsFn: func() (*model.ProxySettings, error) {
return nil, errors.New("boom")
},
}
h := &Handler{
storageService: storage,
logger: log.New(io.Discard, "", 0),
}
req := httptest.NewRequest(http.MethodGet, "/api/settings", nil)
rr := httptest.NewRecorder()
h.GetSettings(rr, req)
if rr.Code != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d", rr.Code)
}
var response model.ErrorResponse
decodeJSONBody(t, rr, &response)
if response.Error != "Failed to get settings" {
t.Fatalf("unexpected error response: %#v", response)
}
}
func TestSaveSettingsRejectsInvalidBodyAndStorageFailures(t *testing.T) {
t.Run("invalid json", func(t *testing.T) {
h := &Handler{
storageService: &stubStorage{},
logger: log.New(io.Discard, "", 0),
}
req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewBufferString(`{"requestHeaderRules":`))
rr := httptest.NewRecorder()
h.SaveSettings(rr, req)
if rr.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rr.Code)
}
var response model.ErrorResponse
decodeJSONBody(t, rr, &response)
if response.Error != "Invalid request body" {
t.Fatalf("unexpected error response: %#v", response)
}
})
t.Run("storage error", func(t *testing.T) {
storage := &stubStorage{
saveSettingsFn: func(settings *model.ProxySettings) error {
return errors.New("boom")
},
}
h := &Handler{
storageService: storage,
logger: log.New(io.Discard, "", 0),
}
req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewBufferString(`{"responseHeaderRules":[{"header":"X-Test","action":"set","value":"1","enabled":true}]}`))
rr := httptest.NewRecorder()
h.SaveSettings(rr, req)
if rr.Code != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d", rr.Code)
}
if storage.saveCalls != 1 {
t.Fatalf("expected one settings save attempt, got %d", storage.saveCalls)
}
var response model.ErrorResponse
decodeJSONBody(t, rr, &response)
if response.Error != "Failed to save settings" {
t.Fatalf("unexpected error response: %#v", response)
}
})
}