-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy.go
243 lines (215 loc) · 5.93 KB
/
proxy.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
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"maps"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
// TODO: this is kind of gross but works ok for now
const headerPrefixSize = 4096
const proxyCacheKeyBytes = 24
const proxyDebug = false
var skipReturnHeaders = map[string]bool{
"Alt-Svc": true,
"Content-Transfer-Encoding": true,
"Transfer-Encoding": true,
}
type proxyHandler struct {
cc *CacheClient
upstreams []url.URL
}
func proxyMain() {
log.SetFlags(0)
log.SetPrefix("nix-gocacheprog mod proxy:")
// the hook ensures GOPROXY is set here. this GOPROXY does not include ourself.
var upstreams []url.URL
for _, up := range strings.Split(os.Getenv("GOPROXY"), ",") {
if u, err := url.Parse(up); err == nil && u.Scheme == "http" || u.Scheme == "https" {
upstreams = append(upstreams, *u)
}
}
uc := initClient()
h := &proxyHandler{
cc: NewCacheClient(uc, uc),
upstreams: upstreams,
}
err := http.ListenAndServe(ProxyListen, h)
if err != nil {
log.Fatalln(err)
}
}
func (h *proxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
var actionID []byte
// only .mod and .zip paths are immutable and should be cached, others are passed through
// wihtout caching.
if strings.HasSuffix(path, ".mod") || strings.HasSuffix(path, ".zip") {
// make cache key
hsh := sha256.New()
fmt.Fprintf(hsh, "gomodproxy v1\n")
fmt.Fprintf(hsh, "path=%s\n", path)
fmt.Fprintf(hsh, "headerPrefixSize=%d\n", headerPrefixSize)
actionID = hsh.Sum(nil)[:proxyCacheKeyBytes]
}
// check if we can get it from cache
if actionID != nil {
err := h.getAndWrite(w, actionID)
if err == nil {
if proxyDebug {
log.Printf("hit %s", path)
}
return
}
if proxyDebug {
log.Printf("miss %s (%s)", path, err)
}
}
// nope, try upstreams
for i, up := range h.upstreams {
islast := i == len(h.upstreams)-1
try := up.JoinPath(path).String()
if proxyDebug {
log.Printf("querying %s", try)
}
outReq, err := http.NewRequestWithContext(req.Context(), http.MethodGet, try, nil)
if err != nil {
log.Fatal(err)
}
res, err := http.DefaultClient.Do(outReq)
if err != nil {
if islast {
log.Printf("http error %s on last upstream", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
log.Printf("http error %s, trying next", err)
continue
}
}
if res.StatusCode != http.StatusOK {
if islast {
log.Printf("http status %s on last upstream", res.Status)
// pass through full response
defer res.Body.Close()
copyHeadersReturn(w, res)
io.Copy(w, res.Body)
return
} else {
log.Printf("http status %s, trying next", res.Status)
res.Body.Close()
continue
}
}
// we got an ok, let's use this
defer res.Body.Close()
copyHeadersReturn(w, res)
if actionID == nil {
if proxyDebug {
log.Printf("passthrough %s", path)
}
io.Copy(w, res.Body)
return
}
if err, tryCopyOnError := h.putAndWrite(w, req, res, actionID); err != nil {
log.Println("put error", err)
if tryCopyOnError {
io.Copy(w, res.Body)
}
return
}
return
}
http.Error(w, "no upstreams", http.StatusNotFound)
}
func (h *proxyHandler) getAndWrite(w http.ResponseWriter, actionID []byte) error {
cacheRes, err := h.cc.get(actionID)
if err != nil {
return err
}
if cacheRes.Err != "" {
return errors.New(cacheRes.Err)
} else if cacheRes.Miss {
return errors.New("cache miss")
} else if cacheRes.DiskPath == "" {
return errors.New("missing disk path")
}
f, err := os.Open(cacheRes.DiskPath)
if err != nil {
return err
}
defer f.Close()
hbuf := make([]byte, headerPrefixSize)
if _, err := io.ReadFull(f, hbuf); err != nil {
return err
}
var headers http.Header
if err := json.Unmarshal(hbuf, &headers); err != nil {
return err
}
// verify matching sizes
if fi, err := f.Stat(); err != nil {
return err
} else if cacheRes.Size != fi.Size() {
return fmt.Errorf("mismatched cache size and disk size: %d != %d", cacheRes.Size, fi.Size())
} else if cl, err := strconv.Atoi(headers.Get("Content-Length")); err != nil {
// this should be there, but if not fill it in
headers.Set("Content-Length", strconv.Itoa(int(cacheRes.Size)))
} else if cl != int(cacheRes.Size)-headerPrefixSize {
return fmt.Errorf("cache had wrong Content-Length header: %d != %d", cl, cacheRes.Size-headerPrefixSize)
}
// all good, start writing response
maps.Copy(w.Header(), headers)
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, f); err != nil {
log.Println("copy error from cache", err)
}
return nil
}
func (h *proxyHandler) putAndWrite(w http.ResponseWriter, req *http.Request, res *http.Response, actionID []byte) (error, bool) {
if res.ContentLength < 0 {
return errors.New("can't cache without ContentLength"), true
}
var hbuf bytes.Buffer
hbuf.Grow(headerPrefixSize)
if err := json.NewEncoder(&hbuf).Encode(res.Header); err != nil {
return err, true
} else if hbuf.Len() > headerPrefixSize {
return errors.New("headers are too big"), true
}
for hbuf.Len() < headerPrefixSize {
hbuf.WriteByte('\n')
}
// if we got this far, the client (Go) should accept the response, any errors from here are
// just our problem.
// we want to stream through but we need an object id first, so we can't use a hash. use a
// random id.
objectID := make([]byte, proxyCacheKeyBytes)
rand.Read(objectID)
concat := io.MultiReader(&hbuf, io.TeeReader(res.Body, w))
if cacheRes, err := h.cc.put(actionID, objectID, int64(hbuf.Len())+res.ContentLength, concat); err != nil {
return err, false
} else if cacheRes.Err != "" {
return errors.New(cacheRes.Err), false
}
return nil, false
}
func copyHeadersReturn(w http.ResponseWriter, res *http.Response) {
for k, vs := range res.Header {
if !skipReturnHeaders[k] {
for _, v := range vs {
w.Header().Add(k, v)
}
}
}
w.WriteHeader(res.StatusCode)
}