Repository navigation
Expand file tree
/
Copy pathupdate_source.go
More file actions
189 lines (174 loc) · 5.11 KB
/
Copy pathupdate_source.go
File metadata and controls
189 lines (174 loc) · 5.11 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
// Copyright 2026 ysicing
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"fmt"
"io"
"net/http"
"runtime"
"slices"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/egoist/mygo"
"github.com/egoist/mygo/netproxy"
_ "embed"
)
//go:embed release.config.json
var releaseConfig []byte
const maxUpdateManifest = 1 << 20
func configureUpdateSource() {
var config struct {
DownloadBase string `json:"downloadBase"`
}
if err := json.Unmarshal(releaseConfig, &config); err != nil || config.DownloadBase == "" {
return
}
transport := netproxy.Transport().Clone()
transport.ResponseHeaderTimeout = 30 * time.Second
mygo.Updater.SetSource(updateSource{
feed: strings.TrimRight(config.DownloadBase, "/") + "/update-" + runtime.GOOS + "-" + runtime.GOARCH + ".json",
current: mygo.App.Version,
client: &http.Client{Transport: transport, CheckRedirect: checkUpdateRedirect},
})
}
func checkUpdateRedirect(request *http.Request, via []*http.Request) error {
if request.URL.Scheme != "https" || len(via) >= 10 {
return http.ErrUseLastResponse
}
return nil
}
type updateSource struct {
feed string
current func() string
client *http.Client
}
func (source updateSource) Manifest(ctx context.Context, _ bool) (io.ReadCloser, error) {
body, err := source.Open(ctx, source.feed)
if err != nil {
return nil, err
}
defer body.Close()
data, err := io.ReadAll(io.LimitReader(body, maxUpdateManifest+1))
if err != nil {
return nil, err
}
if len(data) > maxUpdateManifest {
return nil, fmt.Errorf("update manifest exceeds %d bytes", maxUpdateManifest)
}
return io.NopCloser(bytes.NewReader(withReleaseHistory(data, source.current()))), nil
}
func (source updateSource) Open(ctx context.Context, rawURL string) (io.ReadCloser, error) {
delays := [...]time.Duration{time.Second, 3 * time.Second}
for attempt := 0; ; attempt++ {
requestCtx, cancel := context.WithCancel(ctx)
request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, rawURL, nil)
if err != nil {
cancel()
return nil, err
}
if request.URL.Scheme != "https" {
cancel()
return nil, fmt.Errorf("update URL must use HTTPS: %s", rawURL)
}
request.Header.Set("User-Agent", "mygo-updater")
response, err := source.client.Do(request)
var retryAfter time.Duration
if err == nil {
if response.StatusCode == http.StatusOK {
return &updateBody{ReadCloser: response.Body, cancel: cancel}, nil
}
response.Body.Close()
err = fmt.Errorf("GET %s: %s", rawURL, response.Status)
switch response.StatusCode {
case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway,
http.StatusServiceUnavailable, http.StatusGatewayTimeout:
if seconds, parseErr := strconv.Atoi(strings.TrimSpace(response.Header.Get("Retry-After"))); parseErr == nil && seconds > 0 {
retryAfter = time.Duration(min(seconds, 30)) * time.Second
}
default:
cancel()
return nil, err
}
}
cancel()
if attempt == len(delays) {
return nil, err
}
timer := time.NewTimer(max(delays[attempt], retryAfter))
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-timer.C:
}
}
}
type updateBody struct {
io.ReadCloser
cancel context.CancelFunc
}
func (body *updateBody) Read(buffer []byte) (int, error) {
timer := time.AfterFunc(time.Minute, body.cancel)
defer timer.Stop()
return body.ReadCloser.Read(buffer)
}
func (body *updateBody) Close() error {
body.cancel()
return body.ReadCloser.Close()
}
func withReleaseHistory(data []byte, current string) []byte {
installed, err := semver.StrictNewVersion(current)
if err != nil {
return data
}
var manifest map[string]jsontext.Value
if err := json.Unmarshal(data, &manifest); err != nil {
return data
}
var target, notes string
var history map[string]string
if json.Unmarshal(manifest["version"], &target) != nil || json.Unmarshal(manifest["notes"], ¬es) != nil {
return data
}
if raw := manifest["releaseHistory"]; raw != nil && json.Unmarshal(raw, &history) != nil {
history = nil
}
latest, err := semver.StrictNewVersion(target)
if err != nil || !latest.GreaterThan(installed) {
return data
}
var versions []*semver.Version
for version, entry := range history {
parsed, err := semver.StrictNewVersion(version)
if err == nil && parsed.GreaterThan(installed) && parsed.LessThan(latest) && strings.TrimSpace(entry) != "" {
versions = append(versions, parsed)
}
}
slices.SortFunc(versions, func(left, right *semver.Version) int { return right.Compare(left) })
groups := releaseNoteGroups{items: make(map[string][]string), includeVersions: len(versions) > 0}
if !groups.add(target, notes) {
return data
}
for _, version := range versions {
if !groups.add(version.Original(), history[version.Original()]) {
return data
}
}
grouped := groups.markdown()
if grouped == "" {
return data
}
manifest["notes"], _ = json.Marshal(grouped)
delete(manifest, "releaseHistory")
updated, err := json.Marshal(manifest)
if err != nil || len(updated) > maxUpdateManifest {
return data
}
return updated
}