-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
235 lines (202 loc) · 5.06 KB
/
http.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/alpine-client/pinnacle/sentry"
"github.com/alpine-client/pinnacle/ui"
)
var httpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: false,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
},
}
func (p *Pinnacle) getFromURL(ctx context.Context, url string) (*http.Response, error) {
const maxAttempts = 4
var statusCode int
for i := range maxAttempts {
if i > 0 {
<-time.After(time.Second * time.Duration(2<<i)) // Exponential backoff
}
p.Breadcrumb(ctx, fmt.Sprintf("[%d] making request to %s", i+1, url))
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
request.Header.Set("User-Agent", fmt.Sprintf("Pinnacle/%s (%s; %s)", version, p.os, p.arch))
response, err := httpClient.Do(request)
if err != nil {
sentry.Breadcrumb(ctx, fmt.Sprintf("[%d] request error: %v", i+1, err), slog.LevelError)
continue
}
statusCode = response.StatusCode
p.Breadcrumb(ctx, fmt.Sprintf("[%d] status code: %d", i+1, statusCode))
if statusCode == http.StatusOK {
return response, nil
}
err = response.Body.Close()
if err != nil {
p.Breadcrumb(ctx, fmt.Sprintf("[%d] failed to close body: %v", i+1, err), slog.LevelError)
}
}
return nil, errors.New("internet failure")
}
func (p *Pinnacle) downloadFile(ctx context.Context, url string, path string, pt *ui.ProgressiveTask) error {
resp, err := p.getFromURL(ctx, url)
if err != nil {
return err
}
defer func() {
p.CaptureErr(ctx, resp.Body.Close())
}()
file, err := os.Create(path)
if err != nil {
return err
}
defer func() {
p.CaptureErr(ctx, file.Close())
}()
err = copyResponseWithProgress(file, resp, pt)
return err
}
func copyResponseWithProgress(dst io.Writer, resp *http.Response, pt *ui.ProgressiveTask) error {
var written int64
var err error
buf := make([]byte, 32*1024)
src := resp.Body
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw < 0 || nr < nw {
nw = 0
if ew == nil {
ew = errors.New("invalid write result")
}
}
written += int64(nw)
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
if pt != nil {
pt.UpdateProgress(float64(written) / float64(resp.ContentLength))
}
}
if er != nil {
if !errors.Is(er, io.EOF) {
err = er
}
break
}
}
return err
}
func (p *Pinnacle) fetchSentryDSN() string {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const endpoint = MetadataURL + "/sentry"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
p.logger.Warn(err.Error())
return ""
}
req.Header.Set("User-Agent", fmt.Sprintf("alpine-client/pinnacle/%s (%s)", version, SupportEmail))
resp, err := httpClient.Do(req)
if err != nil {
p.logger.Warn(err.Error())
return ""
}
defer func() {
if err = resp.Body.Close(); err != nil {
p.logger.Warn("unable to close response body", slog.Any("error", err))
}
}()
if resp.StatusCode != http.StatusOK {
p.logger.Warn(fmt.Sprintf("unable to fetch sentry DSN: status code %d", resp.StatusCode))
return ""
}
type response struct {
DSN string `json:"dsn"`
}
var result response
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
p.logger.Warn(err.Error())
return ""
}
return result.DSN
}
func (p *Pinnacle) isUpdateAvailable(c context.Context) bool {
req, err := http.NewRequestWithContext(c, http.MethodGet, GitHubReleaseURL, nil)
if err != nil {
return false
}
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("User-Agent", fmt.Sprintf("alpine-client/pinnacle/%s (%s)", version, SupportEmail))
resp, err := httpClient.Do(req)
if err != nil {
return false
}
defer func() {
if err = resp.Body.Close(); err != nil {
p.logger.WarnContext(c, err.Error())
}
}()
type details struct {
TagName string `json:"tag_name"`
PreRelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
}
var result details
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return false
}
if result.PreRelease {
return false
}
if version == result.TagName {
return false
}
v := strings.Split(version, ".")
r := strings.Split(result.TagName, ".")
if len(v) != 3 || len(r) != 3 {
return false
}
if v[0] == r[0] && v[1] == r[1] {
// major + minor are the same, don't notify
return false
}
published, err := time.Parse(time.RFC3339, result.PublishedAt)
if err != nil {
p.logger.WarnContext(c, err.Error())
return false
}
if published.UTC().Add(24 * time.Hour).Before(time.Now().UTC()) {
return true
}
return false
}