-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmodifyresponse.go
153 lines (137 loc) · 4.64 KB
/
modifyresponse.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
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.
package pkg
import (
"bytes"
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gitpod-io/gitpod/common-go/log"
"github.com/sirupsen/logrus"
)
func (o *OpenVSXProxy) ModifyResponse(r *http.Response) error {
reqid := r.Request.Context().Value(REQUEST_ID_CTX).(string)
key := r.Request.Context().Value(REQUEST_CACHE_KEY_CTX).(string)
logFields := logrus.Fields{
LOG_FIELD_FUNC: "response_handler",
LOG_FIELD_REQUEST_ID: reqid,
LOG_FIELD_REQUEST: key,
LOG_FIELD_STATUS: strconv.Itoa(r.StatusCode),
"response_content_length": r.Header.Get("Content-Length"),
}
start := time.Now()
defer func(ts time.Time) {
duration := time.Since(ts)
o.metrics.DurationResponseProcessingHistogram.Observe(duration.Seconds())
log.
WithFields(logFields).
WithFields(o.DurationLogFields(duration)).
Info("processing response finished")
}(start)
log.WithFields(logFields).Info("handling response")
o.metrics.IncStatusCounter(r.Request, strconv.Itoa(r.StatusCode))
if key == "" {
log.WithFields(logFields).Error("cache key header is missing - sending response as is")
return nil
}
rawBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error reading response raw body")
return err
}
r.Body.Close()
r.Body = ioutil.NopCloser(bytes.NewBuffer(rawBody))
if r.StatusCode >= 500 || r.StatusCode == http.StatusTooManyRequests || r.StatusCode == http.StatusRequestTimeout {
// use cache if exists
bodyLogField := "(binary)"
if utf8.Valid(rawBody) {
bodyStr := string(rawBody)
truncatedSuffix := ""
if len(bodyStr) > 500 {
truncatedSuffix = "... [truncated]"
}
bodyLogField = fmt.Sprintf("%.500s%s", bodyStr, truncatedSuffix)
}
log.
WithFields(logFields).
WithField("body", bodyLogField).
Warn("error from upstream server - trying to use cached response")
cached, ok, err := o.ReadCache(key)
if err != nil {
log.WithFields(logFields).WithError(err).Error("cannot read from cache")
return nil
}
if !ok {
log.WithFields(logFields).Debug("cache has no entry for key")
return nil
}
r.Header = cached.Header
if v := r.Header.Get("Access-Control-Allow-Origin"); v != "" && v != "*" {
r.Header.Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(cached.Body))
r.ContentLength = int64(len(cached.Body))
r.StatusCode = cached.StatusCode
log.WithFields(logFields).Info("used cache response due to an upstream error")
o.metrics.BackupCacheServeCounter.Inc()
return nil
}
// no error (status code < 500)
body := rawBody
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
isCompressedResponse := strings.EqualFold(r.Header.Get("Content-Encoding"), "gzip")
if isCompressedResponse {
gzipReader, err := gzip.NewReader(ioutil.NopCloser(bytes.NewBuffer(rawBody)))
if err != nil {
log.WithFields(logFields).WithError(err)
return nil
}
body, err = ioutil.ReadAll(gzipReader)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error reading compressed response body")
return nil
}
gzipReader.Close()
}
if log.Log.Level >= logrus.DebugLevel {
log.WithFields(logFields).Debugf("replacing %d occurence(s) of '%s' in response body ...", strings.Count(string(body), o.Config.URLUpstream), o.Config.URLUpstream)
}
bodyStr := strings.ReplaceAll(string(body), o.Config.URLUpstream, o.Config.URLLocal)
body = []byte(bodyStr)
if isCompressedResponse {
var b bytes.Buffer
gzipWriter := gzip.NewWriter(&b)
_, err = gzipWriter.Write(body)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error writing compressed response body")
return nil
}
gzipWriter.Close()
body = b.Bytes()
}
} else {
log.WithFields(logFields).Debugf("response is not JSON but '%s', skipping replacing '%s' in response body", contentType, o.Config.URLUpstream)
}
cacheObj := &CacheObject{
Header: r.Header,
Body: body,
StatusCode: r.StatusCode,
}
err = o.StoreCache(key, cacheObj)
if err != nil {
log.WithFields(logFields).WithError(err).Error("error storing response to cache")
} else {
log.WithFields(logFields).Info("successfully stored response to cache")
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
r.ContentLength = int64(len(body))
r.Header.Set("Content-Length", strconv.Itoa(len(body)))
return nil
}