-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_client.go
More file actions
259 lines (218 loc) · 6.3 KB
/
http_client.go
File metadata and controls
259 lines (218 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package honeybadger
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"reflect"
"strings"
"time"
"github.com/deadmanssnitch/honeybadger/apiv1"
"github.com/gofrs/uuid"
)
type HTTPClient struct {
endpoint string
client *http.Client
config *Config
}
type ClientError struct {
code int
temporary bool
}
func (c ClientError) Error() string {
// Messages taken from Honeybadger Ruby gem
switch c.code {
case 402:
return "The project owner's billing information has expired (or the trial has ended).\n" +
"Please check your payment details or email support@honeybadger.io for help."
case 403:
return "The API key is invalid. Please check your API key and try again."
case 429, 503:
return "Your project is currently sending too many errors.\n" +
"This issue should resolve itself once error traffic is reduced."
}
return fmt.Sprintf("Honeybadger API response error: status=%d temporary=%v", c.code, c.temporary)
}
// StatusCode returns the HTTP status code that the server returned.
func (c ClientError) StatusCode() int {
return c.code
}
// Temporary returns true when the server responded with a temporary error and
// the request should be retried.
func (c ClientError) Temporary() bool {
return c.temporary
}
// NewHTTPClient initializes a Client that talks to api.honeybadger.io
func NewHTTPClient(cfg *Config) *HTTPClient {
if cfg == nil {
cfg = NewConfig()
}
return &HTTPClient{
endpoint: strings.TrimSuffix(cfg.Endpoint, "/"),
client: http.DefaultClient,
config: cfg,
}
}
func (c *HTTPClient) SetClient(client *http.Client) {
c.client = client
}
func (c *HTTPClient) SetEndpoint(url string) {
c.endpoint = strings.TrimSuffix(url, "/")
}
func (c *HTTPClient) Config() *Config {
return c.config
}
func (c *HTTPClient) Notify(ctx context.Context, err error) error {
// NOOP when err is nil. This allows callers to not have to check err if they
// don't want to and avoids an invalid state.
if err == nil {
return nil
}
// Make sure we're working with an Error
notice := Wrap(err)
payload := apiv1.Notice{
Notifier: apiv1.Notifier{
Name: "honeybadger",
URL: "https://github.com/honeybadger-io/honeybadger-go",
Version: "0.5.0",
Language: "Go",
},
Error: apiv1.Error{
Token: uuid.Must(uuid.NewV4()).String(),
Class: causeClass(notice.root()),
Message: notice.Error(),
Tags: notice.Tags().Tags(),
},
Request: apiv1.Request{
Context: notice.Request().Context.values,
Component: notice.Request().Component,
Action: notice.Request().Action,
URL: notice.Request().URL,
Session: notice.Request().Session,
CGIData: notice.Request().CGI,
},
Server: apiv1.Server{
EnvironmentName: c.config.Env,
Time: time.Now().UTC(),
PID: os.Getpid(),
Stats: apiv1.GetServerStats(),
ProjectRoot: c.config.Root,
Hostname: c.config.Hostname,
Revision: c.config.Revision,
},
}
// Error.Backtrace
for _, frame := range notice.root().stacktrace() {
payload.Error.Backtrace = append(payload.Error.Backtrace, apiv1.Backtrace{
File: strings.Replace(frame.File, c.config.Root, "[PROJECT_ROOT]", 1),
Number: frame.Line,
Method: frame.Method,
})
}
// Error.Causes
var cause error = notice
for cause != nil {
if notice, ok := cause.(Error); ok {
cause = errors.Unwrap(notice)
ac := apiv1.Cause{
Class: causeClass(cause),
Message: cause.Error(),
}
for _, frame := range notice.stacktrace() {
ac.Backtrace = append(ac.Backtrace, apiv1.Backtrace{
File: strings.Replace(frame.File, c.config.Root, "[PROJECT_ROOT]", 1),
Number: frame.Line,
Method: frame.Method,
})
}
payload.Error.Causes = append(payload.Error.Causes, ac)
} else {
payload.Error.Causes = append(payload.Error.Causes, apiv1.Cause{
Class: causeClass(cause),
Message: cause.Error(),
})
}
cause = errors.Unwrap(cause)
}
// TODO: Filter parameters
// Request.Params
// Converts the url.Values into a map[string]string by grabbing the first
// value for each supplied param.
params := make(map[string]string)
for k, p := range notice.Request().Params {
params[k] = p[0]
}
return c.post(ctx, "/v1/notices", payload)
}
func (c *HTTPClient) post(ctx context.Context, path string, payload interface{}) error {
body := &bytes.Buffer{}
gzip := gzip.NewWriter(body)
enc := json.NewEncoder(gzip)
err := enc.Encode(payload)
if err != nil {
return fmt.Errorf("payload marshal to json: %w", err)
}
err = gzip.Close()
if err != nil {
return fmt.Errorf("gzip payload: %w", err)
}
url := c.endpoint + path
req, err := http.NewRequestWithContext(ctx, "POST", url, body)
if err != nil {
return err
}
// TODO: User-Agent
// TODO: Should gzip be configurable?
req.Header.Set("X-API-Key", c.config.APIKey)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Encoding", "gzip")
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Success
if 200 <= resp.StatusCode && resp.StatusCode < 300 {
return nil
}
// Request hit a rate limit and should be retried once the limit resets.
if resp.StatusCode == http.StatusTooManyRequests {
return ClientError{code: resp.StatusCode, temporary: true}
}
// Server errors should be retried
if 500 <= resp.StatusCode {
return ClientError{code: resp.StatusCode, temporary: true}
}
// Consider all other responses are considered permanent errors.
//
// See: https://docs.honeybadger.io/api/exceptions.html
return ClientError{code: resp.StatusCode, temporary: false}
}
// causeClass finds the nearest cause ancestor that is not an Error or
// fmt.wrapError.
func causeClass(err error) string {
for e := err; e != nil; e = errors.Unwrap(e) {
if hb, ok := e.(Error); ok {
e = hb.root()
continue
}
// Check to see if it is a constant error from the known types.
if s, ok := knownErrors[e]; ok {
return s
}
t := reflect.TypeOf(e).String()
// *fmt.wrapError is returned from `fmt.Errorf("...: %w", err)` and is used
// to add context to an error. The error itself doesn't give an context so
// we want to unwrap it further.
if t == "*fmt.wrapError" {
continue
}
return t
}
return reflect.TypeOf(err).String()
}