Debian Codegraph @

response.go

raw
1 package proton
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io"
8 "math/rand"
9 "net"
10 "net/http"
11 "strconv"
12 "time"
13
14 "github.com/ProtonMail/gopenpgp/v2/crypto"
15 "github.com/go-resty/resty/v2"
16 "github.com/sirupsen/logrus"
17 )
18
19 type Code int
20
21 const (
22 SuccessCode Code = 1000
23 MultiCode Code = 1001
24 InvalidValue Code = 2001
25 AFileOrFolderNameExist Code = 2500
26 ADraftExist Code = 2500
27 AppVersionMissingCode Code = 5001
28 AppVersionBadCode Code = 5003
29 UsernameInvalid Code = 6003 // Deprecated, but still used.
30 PasswordWrong Code = 8002
31 HumanVerificationRequired Code = 9001
32 PaidPlanRequired Code = 10004
33 AuthRefreshTokenInvalid Code = 10013
34 )
35
36 var (
37 ErrFileNameExist = errors.New("a file with that name already exists (Code=2500, Status=422)")
38 ErrFolderNameExist = errors.New("a folder with that name already exists (Code=2500, Status=422)")
39 ErrADraftExist = errors.New("draft already exists on this revision (Code=2500, Status=409)")
40 )
41
42 // APIError represents an error returned by the API.
43 type APIError struct {
44 // Status is the HTTP status code of the response that caused the error.
45 Status int
46
47 // Code is the error code returned by the API.
48 Code Code
49
50 // Message is the error message returned by the API.
51 Message string `json:"Error"`
52
53 // Details contains optional error details which are specific to each request.
54 Details any
55 }
56
57 func (err APIError) Error() string {
58 return fmt.Sprintf("%v (Code=%v, Status=%v)", err.Message, err.Code, err.Status)
59 }
60
61 func (err APIError) DetailsToString() string {
62 if err.Details == nil {
63 return ""
64 }
65
66 bytes, e := json.Marshal(err.Details)
67 if e != nil {
68 return fmt.Sprintf("Failed to generate json: %v", e)
69 }
70
71 return string(bytes)
72 }
73
74 // NetError represents a network error. It is returned when the API is unreachable.
75 type NetError struct {
76 // Cause is the underlying error that caused the network error.
77 Cause error
78
79 // Message is an additional message that describes the network error.
80 Message string
81 }
82
83 func newNetError(err error, message string) *NetError {
84 return &NetError{Cause: err, Message: message}
85 }
86
87 func (err *NetError) Error() string {
88 return fmt.Sprintf("%s: %v", err.Message, err.Cause)
89 }
90
91 func (err *NetError) Unwrap() error {
92 return err.Cause
93 }
94
95 func (err *NetError) Is(target error) bool {
96 _, ok := target.(*NetError)
97 return ok
98 }
99
100 func catchAPIError(_ *resty.Client, res *resty.Response) error {
101 if !res.IsError() {
102 return nil
103 }
104
105 method := "NONE"
106 route := "N/A"
107
108 if res.Request != nil {
109 method = res.Request.Method
110 route = res.Request.URL
111 }
112
113 var err error
114
115 if apiErr, ok := res.Error().(*APIError); ok {
116 apiErr.Status = res.StatusCode()
117 err = apiErr
118 } else {
119 statusCode := res.StatusCode()
120 statusText := res.Status()
121
122 // Catch error that may slip through when APIError deserialization routine fails for whichever reason.
123 if statusCode >= 400 {
124 err = &APIError{
125 Status: statusCode,
126 Code: 0,
127 Message: statusText,
128 }
129 } else {
130 err = fmt.Errorf("%v", res.Status())
131 }
132 }
133
134 return fmt.Errorf(
135 "%v %s %s: %w",
136 res.StatusCode(), method, route, err,
137 )
138 }
139
140 func updateTime(_ *resty.Client, res *resty.Response) error {
141 date, err := time.Parse(time.RFC1123, res.Header().Get("Date"))
142 if err != nil {
143 return err
144 }
145
146 crypto.UpdateTime(date.Unix())
147
148 return nil
149 }
150
151 // nolint:gosec
152 func catchRetryAfter(_ *resty.Client, res *resty.Response) (time.Duration, error) {
153 // 0 and no error means default behaviour which is exponential backoff with jitter.
154 if res.StatusCode() != http.StatusTooManyRequests && res.StatusCode() != http.StatusServiceUnavailable {
155 return 0, nil
156 }
157
158 // Parse the Retry-After header, or fallback to 10 seconds.
159 after, err := strconv.Atoi(res.Header().Get("Retry-After"))
160 if err != nil {
161 after = 10
162 }
163
164 // Add some jitter to the delay.
165 after += rand.Intn(10)
166
167 logrus.WithFields(logrus.Fields{
168 "pkg": "go-proton-api",
169 "status": res.StatusCode(),
170 "url": res.Request.URL,
171 "method": res.Request.Method,
172 "after": after,
173 }).Warn("Too many requests, retrying after delay")
174
175 return time.Duration(after) * time.Second, nil
176 }
177
178 func catchTooManyRequests(res *resty.Response, _ error) bool {
179 return res.StatusCode() == http.StatusTooManyRequests || res.StatusCode() == http.StatusServiceUnavailable
180 }
181
182 func catchDialError(res *resty.Response, err error) bool {
183 return res.RawResponse == nil
184 }
185
186 func catchDropError(_ *resty.Response, err error) bool {
187 if netErr := new(net.OpError); errors.As(err, &netErr) {
188 return true
189 }
190
191 return false
192 }
193
194 // parseResponse should be used as post-processing of response when request is
195 // called with resty.SetDoNotParseResponse(off).
196 //
197 // In this case the resty is not processing request at all including http
198 // status check or APIerror parsing. Hence, the returned error would be nil
199 // even on non-200 reponsenses.
200 //
201 // This function also closes the response body.
202 func parseResponse(res *resty.Response, err error) (*resty.Response, error) {
203 if err != nil || res.StatusCode() == 200 {
204 return res, err
205 }
206
207 method := "NONE"
208 route := "N/A"
209
210 if res.Request != nil {
211 method = res.Request.Method
212 route = res.Request.URL
213 }
214
215 apiErr, ok := parseRawAPIError(res.RawBody())
216 if !ok {
217 apiErr = &APIError{
218 Code: 0,
219 Message: res.Status(),
220 }
221 }
222
223 apiErr.Status = res.StatusCode()
224
225 return res, fmt.Errorf(
226 "%v %s %s: %w",
227 res.StatusCode(), method, route, apiErr,
228 )
229 }
230
231 func parseRawAPIError(rawResponse io.ReadCloser) (*APIError, bool) {
232 apiErr := APIError{}
233 defer rawResponse.Close()
234
235 body, err := io.ReadAll(rawResponse)
236 if err != nil {
237 return &apiErr, false
238 }
239
240 if err := json.Unmarshal(body, &apiErr); err != nil {
241 return &apiErr, false
242 }
243
244 return &apiErr, true
245 }