-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
381 lines (331 loc) · 10.6 KB
/
handler.go
File metadata and controls
381 lines (331 loc) · 10.6 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
startedAt := time.Now()
summary := requestSummary{
url: redactQuery(strings.TrimPrefix(r.URL.Path, "/")),
cache: "none",
source: "local",
statusCode: http.StatusInternalServerError,
}
defer func() {
summary.totalDuration = time.Since(startedAt)
logRequestSummary(summary)
}()
aggregateMetrics.recordRequest()
if !isLocalhost(r.RemoteAddr) {
log.Println("Forbidden:", r.RemoteAddr)
summary.statusCode = http.StatusForbidden
summary.errorClass = "forbidden_remote"
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
urlPath, _ := url.PathUnescape(r.URL.Path)
urlPath = strings.TrimPrefix(urlPath, "/")
cleanedURLPath := redactQuery(urlPath)
summary.url = cleanedURLPath
good, long, minURLSize := isAllowedURL(urlPath)
if !good {
log.Println("Forbidden:", cleanedURLPath)
summary.statusCode = http.StatusForbidden
summary.errorClass = "forbidden_path"
http.Error(w, "Forbidden path", http.StatusForbidden)
return
}
cacheFile, err := cacheBodyFilename(urlPath, long)
if err != nil {
log.Println("Invalid cache path")
summary.statusCode = http.StatusInternalServerError
summary.errorClass = "cache_path"
http.Error(w, "Invalid cache path", http.StatusInternalServerError)
return
}
cacheKey := generateCacheKey(urlPath)
lockEntry := acquireCacheLock(cacheKey)
lockEntry.mu.Lock()
defer func() {
lockEntry.mu.Unlock()
releaseCacheLock(cacheKey, lockEntry)
}()
if err := serveFromCache(w, cleanedURLPath, cacheFile, &summary); err == nil {
return
} else if !errors.Is(err, os.ErrNotExist) {
log.Printf("Cache read failed for %s: %v", cleanedURLPath, err)
}
aggregateMetrics.recordCacheMiss()
summary.cache = "miss"
summary.source = "upstream"
waitStartedAt := time.Now()
if err := waitForUpstreamSlot(r.Context()); err != nil {
summary.throttleWait = time.Since(waitStartedAt)
aggregateMetrics.recordThrottleWait(summary.throttleWait)
summary.statusCode = http.StatusRequestTimeout
summary.errorClass = "client_canceled"
aggregateMetrics.recordClientCancel()
log.Println(cleanedURLPath + " : request canceled before upstream fetch")
http.Error(w, cleanedURLPath+" : request canceled before upstream fetch", http.StatusRequestTimeout)
return
}
summary.throttleWait = time.Since(waitStartedAt)
aggregateMetrics.recordThrottleWait(summary.throttleWait)
fetchCtx, cancel := context.WithTimeout(r.Context(), fetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(fetchCtx, http.MethodGet, urlPath, nil)
if err != nil {
summary.statusCode = http.StatusBadRequest
summary.errorClass = "invalid_upstream_url"
log.Println(cleanedURLPath + " : invalid upstream URL")
http.Error(w, cleanedURLPath+" : invalid upstream URL", http.StatusBadRequest)
return
}
aggregateMetrics.recordUpstreamFetch()
resp, err := upstreamClient.Do(req)
if err != nil {
statusCode, detail, errorClass := classifyFetchError(err)
summary.statusCode = statusCode
summary.errorClass = errorClass
updateErrorMetrics(errorClass)
log.Println(cleanedURLPath + " : " + detail)
http.Error(w, cleanedURLPath+" : "+detail, statusCode)
return
}
defer resp.Body.Close()
summary.upstreamStatus = resp.StatusCode
aggregateMetrics.recordUpstreamStatus(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
summary.statusCode = mapUpstreamStatus(resp.StatusCode)
summary.errorClass = upstreamStatusClass(resp.StatusCode)
log.Printf("%s: upstream returned %s", cleanedURLPath, resp.Status)
http.Error(w, fmt.Sprintf("%v: upstream returned %v", cleanedURLPath, resp.Status), summary.statusCode)
return
}
downloadedFile, bodyLen, err := downloadUpstreamBody(cleanedURLPath, cacheFile, resp, &summary)
if err != nil {
statusCode, detail, errorClass := classifyFetchError(err)
summary.statusCode = statusCode
summary.errorClass = errorClass
updateErrorMetrics(errorClass)
log.Println(cleanedURLPath + " : " + detail)
http.Error(w, cleanedURLPath+" : "+detail, statusCode)
return
}
defer os.Remove(downloadedFile)
headers := preserveResponseHeaders(resp.Header, bodyLen)
meta := cacheMetadata{
Version: cacheFormatVersion,
Status: http.StatusOK,
Headers: headers,
ContentLength: bodyLen,
}
servePath := downloadedFile
if shouldCacheResponse(bodyLen, minURLSize) {
if err := commitCacheEntry(downloadedFile, cacheFile, meta); err != nil {
log.Printf("Failed to commit cache for %s: %v", cleanedURLPath, err)
} else {
servePath = cacheFile
}
} else if bodyLen < minCacheSize {
log.Println("Not caching (minCacheSize):", bodyLen, "bytes:", cleanedURLPath)
} else {
log.Println("Not caching (min url size):", bodyLen, "bytes:", cleanedURLPath)
}
summary.statusCode = http.StatusOK
summary.errorClass = ""
summary.bytesServed, err = streamFileByName(w, servePath, http.StatusOK, headers, bodyLen)
aggregateMetrics.addBytesServed(summary.bytesServed)
if err != nil {
if isClientCanceledError(err) {
summary.errorClass = "client_canceled"
aggregateMetrics.recordClientCancel()
log.Printf("%s : client canceled while writing response", cleanedURLPath)
return
}
summary.errorClass = "response_write"
log.Printf("%s : failed to write response: %v", cleanedURLPath, err)
}
}
func serveFromCache(w http.ResponseWriter, cleanedURLPath, cacheFile string, summary *requestSummary) error {
bodyFile, meta, err := openCachedBody(cacheFile)
if err != nil {
return err
}
defer bodyFile.Close()
summary.cache = "hit"
summary.source = "cache"
summary.statusCode = meta.Status
summary.upstreamStatus = meta.Status
bytesServed, err := streamFile(w, bodyFile, meta.Status, meta.Headers, meta.ContentLength)
summary.bytesServed = bytesServed
if err != nil {
if isClientCanceledError(err) {
summary.errorClass = "client_canceled"
aggregateMetrics.recordClientCancel()
log.Printf("%s : client canceled while writing cached response", cleanedURLPath)
return nil
}
summary.errorClass = "cache_write"
return err
}
addSavedBytes(uint64(bytesServed))
aggregateMetrics.recordCacheHit(bytesServed, bytesServed)
log.Println("From Cache:", cleanedURLPath)
return nil
}
func cacheBodyFilename(urlPath string, long bool) (string, error) {
rootDir := shortCacheDir
if long {
rootDir = longCacheDir
}
return safeJoin(rootDir, generateCacheKey(urlPath))
}
func downloadUpstreamBody(cleanedURLPath, cacheFile string, resp *http.Response, summary *requestSummary) (string, int64, error) {
tempFile, err := os.CreateTemp(filepath.Dir(cacheFile), filepath.Base(cacheFile)+".tmp-*")
if err != nil {
return "", 0, err
}
tempName := tempFile.Name()
defer func() {
tempFile.Close()
}()
written, copyErr := io.Copy(tempFile, resp.Body)
summary.bytesDownloaded = written
aggregateMetrics.addBytesDownloaded(written)
if copyErr != nil {
os.Remove(tempName)
return "", written, copyErr
}
if resp.ContentLength >= 0 && written != resp.ContentLength {
os.Remove(tempName)
return "", written, fmt.Errorf("content length mismatch: expected %d got %d", resp.ContentLength, written)
}
if err := tempFile.Close(); err != nil {
os.Remove(tempName)
return "", written, err
}
log.Println("Downloaded:", cleanedURLPath)
return tempName, written, nil
}
func commitCacheEntry(tempName, cacheFile string, meta cacheMetadata) error {
metaFile := cacheMetadataFilename(cacheFile)
metaTempFile, err := os.CreateTemp(filepath.Dir(metaFile), filepath.Base(metaFile)+".tmp-*")
if err != nil {
return err
}
metaTempName := metaTempFile.Name()
if err := metaTempFile.Close(); err != nil {
os.Remove(metaTempName)
return err
}
if err := writeCacheMetadata(metaTempName, meta); err != nil {
os.Remove(metaTempName)
return err
}
if err := os.Rename(tempName, cacheFile); err != nil {
os.Remove(metaTempName)
return err
}
if err := os.Rename(metaTempName, metaFile); err != nil {
os.Remove(metaTempName)
if removeErr := os.Remove(cacheFile); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
log.Printf("Failed to roll back cache body for %s after metadata error: %v", cacheFile, removeErr)
}
return err
}
return nil
}
func shouldCacheResponse(bodyLen int64, minURLSize int) bool {
if bodyLen < minCacheSize {
return false
}
return bodyLen > int64(minURLSize)
}
func classifyFetchError(err error) (int, string, string) {
if errors.Is(err, context.Canceled) {
return http.StatusRequestTimeout, "request canceled", "client_canceled"
}
if errors.Is(err, context.DeadlineExceeded) {
return http.StatusGatewayTimeout, "upstream timeout", "upstream_timeout"
}
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
return http.StatusGatewayTimeout, "upstream timeout", "upstream_timeout"
}
var urlErr *url.Error
if errors.As(err, &urlErr) {
if errors.Is(urlErr.Err, context.Canceled) {
return http.StatusRequestTimeout, "request canceled", "client_canceled"
}
if errors.Is(urlErr.Err, context.DeadlineExceeded) {
return http.StatusGatewayTimeout, "upstream timeout", "upstream_timeout"
}
var innerNetErr net.Error
if errors.As(urlErr.Err, &innerNetErr) && innerNetErr.Timeout() {
return http.StatusGatewayTimeout, "upstream timeout", "upstream_timeout"
}
return http.StatusBadGateway, "failed to reach upstream", "upstream_transport"
}
if isContentLengthMismatch(err) {
return http.StatusBadGateway, "data ended early", "incomplete_upstream_body"
}
return http.StatusBadGateway, "failed to fetch upstream response", "upstream_transport"
}
func mapUpstreamStatus(statusCode int) int {
switch {
case statusCode >= 500:
return http.StatusBadGateway
case statusCode == http.StatusTooManyRequests:
return http.StatusTooManyRequests
case statusCode >= 400:
return statusCode
default:
return http.StatusBadGateway
}
}
func updateErrorMetrics(errorClass string) {
switch errorClass {
case "client_canceled":
aggregateMetrics.recordClientCancel()
case "upstream_timeout":
aggregateMetrics.recordUpstreamTimeout()
}
}
func upstreamStatusClass(statusCode int) string {
switch {
case statusCode == 429:
return "upstream_429"
case statusCode >= 500:
return "upstream_5xx"
case statusCode >= 400:
return "upstream_4xx"
default:
return ""
}
}
func isClientCanceledError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, context.Canceled) {
return true
}
if errors.Is(err, net.ErrClosed) {
return true
}
return false
}
func isContentLengthMismatch(err error) bool {
return err != nil && strings.Contains(err.Error(), "content length mismatch")
}