返回 DeepSeek-Reasonix
recovery.go
根目录 / internal / provider / recovery.go
1 package provider
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "time"
8 )
9
10 type managedRecoveryKey struct{}
11
12 // WithManagedRecovery gives the caller sole ownership of protocol/context
13 // repairs. It does not enable transport retries or change request bytes.
14 func WithManagedRecovery(ctx context.Context) context.Context {
15 return context.WithValue(ctx, managedRecoveryKey{}, true)
16 }
17 func ManagedRecovery(ctx context.Context) bool {
18 v, _ := ctx.Value(managedRecoveryKey{}).(bool)
19 return v
20 }
21
22 // RecoveryFailure is local diagnostic state, never part of a model request.
23 type RecoveryFailure struct {
24 Phase string
25 Status int
26 Code string
27 RetryAfter time.Duration
28 Retryable bool
29 }
30
31 func ClassifyRecovery(err error) RecoveryFailure {
32 f := RecoveryFailure{Phase: "unknown"}
33 if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
34 return f
35 }
36 if errors.As(err, new(*RequestSendTimeoutError)) {
37 f.Phase, f.Code = "send", "request_send_timeout"
38 return f
39 }
40 if protocolFailureIsTerminal(err) {
41 f.Phase, f.Code = "protocol", HTTP2TransportCode(err)
42 return f
43 }
44 if exhausted := AsRecoveryWaitExhausted(err); exhausted != nil {
45 f.Phase, f.Status, f.Code = exhausted.Phase, exhausted.Status, exhausted.Code
46 return f
47 }
48 if q := AsQuotaError(err); q != nil {
49 f.Phase, f.Status, f.Code = "quota", q.Status, q.Code
50 return f
51 }
52 var auth *AuthError
53 if errors.As(err, &auth) {
54 f.Phase = "auth"
55 return f
56 }
57 if AsContextLimitError(err) != nil || AsOutputLimitError(err) != nil {
58 f.Phase = "limit"
59 return f
60 }
61 if AsReasoningReplayError(err) != nil {
62 f.Phase = "protocol"
63 return f
64 }
65 var api *APIError
66 if errors.As(err, &api) {
67 f.Phase, f.Status, f.RetryAfter = "headers", api.Status, api.RetryAfter
68 var body struct {
69 Error struct {
70 Code string `json:"code"`
71 Type string `json:"type"`
72 } `json:"error"`
73 }
74 if json.Unmarshal([]byte(api.Body), &body) == nil {
75 f.Code = body.Error.Code
76 if f.Code == "" {
77 f.Code = body.Error.Type
78 }
79 }
80 f.Retryable = RetryableStatus(api.Status) || api.Status == 409
81 if api.ShouldRetry == "false" {
82 f.Retryable = false
83 }
84 return f
85 }
86 if IsStreamInterrupted(err) {
87 f.Phase, f.Retryable = "stream", true
88 return f
89 }
90 if errors.Is(err, ErrEmptyResponse) {
91 f.Phase, f.Retryable = "empty", true
92 return f
93 }
94 if IsConnReset(err) {
95 f.Phase, f.Retryable = "connect", true
96 }
97 return f
98 }
99
99 lines GO