-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfetcher.go
293 lines (248 loc) · 6.06 KB
/
fetcher.go
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package ant
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// StaticAgent is a static user agent string.
type StaticAgent string
// String implementation.
func (sa StaticAgent) String() string {
return string(sa)
}
var (
// UserAgent is the default user agent to use.
//
// The user agent is used by default when fetching
// pages and robots.txt.
UserAgent = StaticAgent("antbot")
// DefaultFetcher is the default fetcher to use.
//
// It uses the default client and default user agent.
DefaultFetcher = &Fetcher{
Client: DefaultClient,
UserAgent: UserAgent,
}
// MinBackoff to use when the fetcher retries.
//
// Must be less than MaxBackoff, otherwise
// the fetcher returns an error.
minBackoff = 50 * time.Millisecond
// MaxBackoff to use when the fetcher retries.
//
// Must be greater than MinBackoff, otherwise the
// fetcher returns an error.
maxBackoff = 1 * time.Second
)
// FetchError represents a fetch error.
type FetchError struct {
URL *url.URL
Status int
}
// Error implementation.
func (err FetchError) Error() string {
return fmt.Sprintf("ant: fetch %q - %d %s",
err.URL,
err.Status,
http.StatusText(err.Status),
)
}
// Temporary returns true if the HTTP status code
// generally means the error is temporary.
func (err FetchError) Temporary() bool {
return err.Status == 503 || // Service Unavailable.
err.Status == 504 || // Gateway Timeout.
err.Status == 429 // Too many requests.
}
// Fetch fetches a page from URL.
func Fetch(ctx context.Context, rawurl string) (*Page, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return DefaultFetcher.Fetch(ctx, u)
}
// Fetcher implements a page fetcher.
type Fetcher struct {
// Client is the client to use.
//
// If nil, ant.DefaultClient is used.
Client Client
// UserAgent is the user agent to use.
//
// It implements the fmt.Stringer interface
// to allow user agent spoofing when needed.
//
// If nil, the client decides the user agent.
UserAgent fmt.Stringer
// MaxAttempts is the maximum request attempts to make.
//
// When <= 0, it defaults to 5.
MaxAttempts int
// MinBackoff to use when the fetcher retries.
//
// Must be less than MaxBackoff, otherwise
// the fetcher returns an error.
//
// Defaults to `50ms`.
MinBackoff time.Duration
// MaxBackoff to use when the fetcher retries.
//
// Must be greater than MinBackoff, otherwise the
// fetcher returns an error.
//
// Defaults to `1s`.
MaxBackoff time.Duration
}
// Fetch fetches a page by URL.
//
// The method uses the configured client to make a new request
// parse the response and return a page.
//
// The method returns a nil page and nil error when the status
// code is 404.
//
// The will retry the request when the status code is temporary
// or when a temporary network error occures.
//
// The returned page contains the response's body, the body must
// be read until EOF and closed so that the client can re-use the
// underlying TCP connection.
func (f *Fetcher) Fetch(ctx context.Context, url *URL) (*Page, error) {
var maxAttempts = f.maxAttempts()
var attempt int
var resp *http.Response
var err error
for {
if attempt++; attempt > maxAttempts {
return nil, fmt.Errorf(
"ant: max attempts of %d reached - %w",
maxAttempts,
err,
)
}
if resp, err = f.fetch(ctx, url); err == nil {
break
}
f.discard(resp)
if isTemporary(err) {
if err := f.backoff(ctx, attempt); err != nil {
return nil, err
}
continue
}
if err, ok := err.(*FetchError); ok {
if err.Status == 404 {
return nil, nil
}
}
return nil, err
}
return &Page{
URL: resp.Request.URL,
Header: resp.Header,
body: resp.Body,
}, nil
}
// Fetch fetches a new page by URL.
func (f *Fetcher) fetch(ctx context.Context, url *URL) (*http.Response, error) {
var client = f.client()
req, err := http.NewRequestWithContext(ctx, "GET", url.String(), nil)
if err != nil {
return nil, fmt.Errorf("ant: new request - %w", err)
}
for k, v := range f.headers() {
req.Header[k] = v
}
resp, err := client.Do(req)
if err != nil {
return resp, fmt.Errorf("ant: %s %q - %w", req.Method, req.URL, err)
}
if resp.StatusCode >= 400 {
return resp, &FetchError{
URL: resp.Request.URL,
Status: resp.StatusCode,
}
}
return resp, nil
}
// Discard discards the given response.
func (f *Fetcher) discard(r *http.Response) {
if r != nil {
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
}
}
// MaxAttempts returns the max attempts.
func (f *Fetcher) maxAttempts() int {
if f.MaxAttempts > 0 {
return f.MaxAttempts
}
return 5
}
// Headers returns all headers.
func (f *Fetcher) headers() http.Header {
var hdr = make(http.Header)
hdr.Set("Accept", "text/html; charset=UTF-8")
hdr.Set("User-Agent", f.userAgent())
return hdr
}
// UserAgent returns the user agent to use.
func (f *Fetcher) userAgent() string {
if ua := f.UserAgent; ua != nil {
return ua.String()
}
return UserAgent.String()
}
// Client returns the client to use.
func (f *Fetcher) client() Client {
if f.Client != nil {
return f.Client
}
return DefaultClient
}
// Backoff performs the backoff.
//
// TODO: configurable backoff duration, jitter...?
func (f *Fetcher) backoff(ctx context.Context, attempt int) error {
var min = f.minBackoff()
var max = f.maxBackoff()
var dur = time.Duration(attempt*attempt) * min
if min >= max {
return fmt.Errorf("ant: min backoff must be greater than max backoff")
}
if dur > max {
dur = max
}
var timer = time.NewTimer(dur)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// MinBackoff returns the min backoff.
func (f *Fetcher) minBackoff() time.Duration {
if f.MinBackoff > 0 {
return f.MinBackoff
}
return minBackoff
}
// MaxBackoff returns the min backoff.
func (f *Fetcher) maxBackoff() time.Duration {
if f.MaxBackoff > 0 {
return f.MaxBackoff
}
return maxBackoff
}
// IsTemporary returns true if the error is temporary.
func isTemporary(err error) bool {
t, ok := err.(interface{ Temporary() bool })
return ok && t.Temporary()
}