fix(growth): harden AI jobs and cost controls

This commit is contained in:
2026-08-21 01:48:47 +03:30
parent 86e9d7c5f9
commit a15c04cac1
13 changed files with 366 additions and 78 deletions

View File

@@ -127,3 +127,45 @@ func TestGrowthSSEAuthorizesBeforeSettingStreamHeaders(t *testing.T) {
t.Fatalf("status=%d content-type=%q", response.Code, response.Header().Get("Content-Type"))
}
}
func TestGrowthSSERejectsWhenGlobalCapacityIsFull(t *testing.T) {
t.Parallel()
slots := make(chan struct{}, 1)
slots <- struct{}{}
reads := 0
service := fakeGrowthService{get: func(int64, string) (growthreport.Record, error) {
reads++
return growthreport.Record{Report: growthreport.Report{ReportID: "growth_0123456789abcdef01234567", Status: growthreport.StatusQueued}}, nil
}}
server := &Server{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), growth: service, growthSSESlots: slots}
request := httptest.NewRequest("GET", "/", nil)
request.SetPathValue("reportId", "growth_0123456789abcdef01234567")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, identity.Session{MerchantID: 7}))
response := httptest.NewRecorder()
server.growthReportEvents(response, request)
if response.Code != http.StatusTooManyRequests || reads != 0 {
t.Fatalf("status=%d database reads=%d", response.Code, reads)
}
}
func TestGrowthSSEEndsAtConfiguredDeadline(t *testing.T) {
t.Parallel()
reads := 0
service := fakeGrowthService{get: func(int64, string) (growthreport.Record, error) {
reads++
return growthreport.Record{Report: growthreport.Report{ReportID: "growth_0123456789abcdef01234567", Status: growthreport.StatusQueued, UpdatedAt: time.Unix(int64(reads), 0)}}, nil
}}
server := &Server{logger: slog.New(slog.NewTextHandler(io.Discard, nil)), growth: service, growthSSESlots: make(chan struct{}, 1), growthSSEMaxDuration: 5 * time.Millisecond, growthSSEPollInterval: time.Millisecond}
request := httptest.NewRequest("GET", "/", nil)
request.SetPathValue("reportId", "growth_0123456789abcdef01234567")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, identity.Session{MerchantID: 7}))
response := httptest.NewRecorder()
started := time.Now()
server.growthReportEvents(response, request)
if elapsed := time.Since(started); elapsed > 250*time.Millisecond {
t.Fatalf("stream remained open for %s", elapsed)
}
if reads < 1 || reads > 10 {
t.Fatalf("database reads=%d", reads)
}
}