Files
TradarrV2/backend/internal/ai/generation_response.go

65 lines
2.0 KiB
Go

package ai
import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
)
const maxGenerationResponseBytes = 2 << 20
type generationReadError struct{ cause error }
func (e *generationReadError) Error() string { return "provider generation response unavailable" }
func (e *generationReadError) Unwrap() error { return e.cause }
// Preserve only structured HTTP status and allowlisted error identifiers. Error
// messages and response bodies never become error strings or log arguments.
func readGenerationResponse(resp *http.Response) ([]byte, error) {
maximum := maxGenerationResponseBytes
if resp.StatusCode != http.StatusOK {
maximum = 64 << 10
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, int64(maximum)+1))
if resp.StatusCode != http.StatusOK {
code := ""
if err == nil && len(raw) <= maximum {
code = generationErrorCode(raw)
}
return nil, &summaryHTTPError{status: resp.StatusCode, code: code, err: errors.New("provider generation rejected")}
}
if err != nil {
return nil, &generationReadError{cause: err}
}
if len(raw) > maximum {
return nil, errors.New("provider generation response unavailable")
}
return raw, nil
}
func generationErrorCode(raw []byte) string {
var payload struct {
Error struct {
Code any `json:"code"`
Type, Status string
Details []struct{ Reason string }
}
}
if json.Unmarshal(raw, &payload) != nil {
return ""
}
code, _ := payload.Error.Code.(string)
values := []string{code, payload.Error.Type, payload.Error.Status}
for _, detail := range payload.Error.Details {
values = append(values, detail.Reason)
}
for _, value := range values {
switch code := strings.ToLower(value); code {
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired", "model_not_found", "not_found_error", "not_found", "rate_limit_error", "rate_limit_exceeded", "resource_exhausted", "deadline_exceeded", "timeout_error":
return code
}
}
return ""
}