Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/openvsx-proxy/pkg/errorhandler.go
2498 views
1
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package pkg
6
7
import (
8
"net/http"
9
"time"
10
11
"github.com/gitpod-io/gitpod/common-go/log"
12
"github.com/sirupsen/logrus"
13
)
14
15
func (o *OpenVSXProxy) ErrorHandler(rw http.ResponseWriter, r *http.Request, e error) {
16
reqid := r.Context().Value(REQUEST_ID_CTX).(string)
17
key, ok := r.Context().Value(REQUEST_CACHE_KEY_CTX).(string)
18
19
logFields := logrus.Fields{
20
LOG_FIELD_FUNC: "error_handler",
21
LOG_FIELD_REQUEST_ID: reqid,
22
LOG_FIELD_REQUEST: key,
23
LOG_FIELD_STATUS: "error",
24
}
25
26
start := time.Now()
27
defer func(ts time.Time) {
28
duration := time.Since(ts)
29
o.metrics.DurationResponseProcessingHistogram.Observe(duration.Seconds())
30
log.
31
WithFields(logFields).
32
WithFields(o.DurationLogFields(duration)).
33
Info("processing error finished")
34
}(start)
35
36
log.WithFields(logFields).WithError(e).Warn("handling error")
37
o.metrics.IncStatusCounter(r, "error")
38
39
if !ok {
40
return
41
}
42
43
if key == "" {
44
log.WithFields(logFields).Error("cache key header is missing")
45
rw.WriteHeader(http.StatusBadGateway)
46
return
47
}
48
49
cached, ok, err := o.ReadCache(key)
50
if err != nil {
51
log.WithFields(logFields).WithError(err).Error("cannot read from cache")
52
rw.WriteHeader(http.StatusBadGateway)
53
return
54
}
55
if !ok {
56
log.WithFields(logFields).Debug("cache has no entry for key")
57
rw.WriteHeader(http.StatusBadGateway)
58
return
59
}
60
for k, v := range cached.Header {
61
for i, val := range v {
62
if i == 0 {
63
rw.Header().Set(k, val)
64
} else {
65
rw.Header().Add(k, val)
66
}
67
}
68
}
69
if v := rw.Header().Get("Access-Control-Allow-Origin"); v != "" && v != "*" {
70
rw.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
71
}
72
rw.WriteHeader(cached.StatusCode)
73
rw.Write(cached.Body)
74
log.WithFields(logFields).Debug("used cached response due to a proxy error")
75
o.metrics.BackupCacheServeCounter.Inc()
76
}
77
78