summaryrefslogtreecommitdiff
path: root/modules/retry/retry.go
blob: 9c002750de7282170dd06edf30936db344a02e1c (plain) (blame)
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package retry

import (
	"errors"
	"io"
	"net"
	"net/http"
	"slices"
	"strconv"
	"time"

	"github.com/philippta/flyscrape"
)

func init() {
	flyscrape.RegisterModule(Module{})
}

type Module struct {
	ticker    *time.Ticker
	semaphore chan struct{}

	RetryDelays []time.Duration
}

func (Module) ModuleInfo() flyscrape.ModuleInfo {
	return flyscrape.ModuleInfo{
		ID:  "retry",
		New: func() flyscrape.Module { return new(Module) },
	}
}

func (m *Module) Provision(flyscrape.Context) {
	if m.RetryDelays == nil {
		m.RetryDelays = defaultRetryDelays
	}
}

func (m *Module) AdaptTransport(t http.RoundTripper) http.RoundTripper {
	return flyscrape.RoundTripFunc(func(r *http.Request) (*http.Response, error) {
		resp, err := t.RoundTrip(r)
		if !shouldRetry(resp, err) {
			return resp, err
		}

		for _, delay := range m.RetryDelays {
			drainBody(resp, err)

			time.Sleep(retryAfter(resp, delay))

			resp, err = t.RoundTrip(r)
			if !shouldRetry(resp, err) {
				break
			}
		}

		return resp, err
	})
}

func shouldRetry(resp *http.Response, err error) bool {
	statusCodes := []int{
		http.StatusRequestTimeout,
		http.StatusTooEarly,
		http.StatusTooManyRequests,
		http.StatusInternalServerError,
		http.StatusBadGateway,
		http.StatusServiceUnavailable,
		http.StatusGatewayTimeout,
	}

	if resp != nil {
		if slices.Contains(statusCodes, resp.StatusCode) {
			return true
		}
	}
	if err == nil {
		return false
	}
	if _, ok := err.(net.Error); ok {
		return true
	}
	if errors.Is(err, io.ErrUnexpectedEOF) {
		return true
	}

	return false
}

func drainBody(resp *http.Response, err error) {
	if err == nil && resp != nil && resp.Body != nil {
		io.Copy(io.Discard, resp.Body)
		resp.Body.Close()
	}
}

func retryAfter(resp *http.Response, fallback time.Duration) time.Duration {
	if resp == nil {
		return fallback
	}

	timeexp := resp.Header.Get("Retry-After")
	if timeexp == "" {
		return fallback
	}

	if seconds, err := strconv.Atoi(timeexp); err == nil {
		return time.Duration(seconds) * time.Second
	}

	formats := []string{
		time.RFC1123, // HTTP Spec
		time.RFC1123Z,
		time.ANSIC,
		time.UnixDate,
		time.RubyDate,
		time.RFC822,
		time.RFC822Z,
		time.RFC850,
		time.RFC3339,
	}
	for _, format := range formats {
		if t, err := time.Parse(format, timeexp); err == nil {
			return t.Sub(time.Now())
		}
	}

	return fallback
}

var defaultRetryDelays = []time.Duration{
	1 * time.Second,
	2 * time.Second,
	5 * time.Second,
	10 * time.Second,
}

var (
	_ flyscrape.TransportAdapter = (*Module)(nil)
	_ flyscrape.Provisioner      = (*Module)(nil)
)