forked from kedacore/http-add-on
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_handlers.go
89 lines (81 loc) · 2.72 KB
/
proxy_handlers.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
package main
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"strconv"
"time"
"github.com/go-logr/logr"
"github.com/kedacore/http-add-on/interceptor/config"
"github.com/kedacore/http-add-on/interceptor/handler"
kedanet "github.com/kedacore/http-add-on/pkg/net"
"github.com/kedacore/http-add-on/pkg/util"
)
type forwardingConfig struct {
waitTimeout time.Duration
respHeaderTimeout time.Duration
forceAttemptHTTP2 bool
maxIdleConns int
idleConnTimeout time.Duration
tlsHandshakeTimeout time.Duration
expectContinueTimeout time.Duration
}
func newForwardingConfigFromTimeouts(t *config.Timeouts) forwardingConfig {
return forwardingConfig{
waitTimeout: t.WorkloadReplicas,
respHeaderTimeout: t.ResponseHeader,
forceAttemptHTTP2: t.ForceHTTP2,
maxIdleConns: t.MaxIdleConns,
idleConnTimeout: t.IdleConnTimeout,
tlsHandshakeTimeout: t.TLSHandshakeTimeout,
expectContinueTimeout: t.ExpectContinueTimeout,
}
}
// newForwardingHandler takes in the service URL for the app backend
// and forwards incoming requests to it. Note that it isn't multitenant.
// It's intended to be deployed and scaled alongside the application itself.
//
// fwdSvcURL must have a valid scheme in it. The best way to do this is
// creating a URL with url.Parse("https://...")
func newForwardingHandler(
lggr logr.Logger,
dialCtxFunc kedanet.DialContextFunc,
waitFunc forwardWaitFunc,
fwdCfg forwardingConfig,
tlsCfg *tls.Config,
) http.Handler {
roundTripper := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialCtxFunc,
ForceAttemptHTTP2: fwdCfg.forceAttemptHTTP2,
MaxIdleConns: fwdCfg.maxIdleConns,
IdleConnTimeout: fwdCfg.idleConnTimeout,
TLSHandshakeTimeout: fwdCfg.tlsHandshakeTimeout,
ExpectContinueTimeout: fwdCfg.expectContinueTimeout,
ResponseHeaderTimeout: fwdCfg.respHeaderTimeout,
TLSClientConfig: tlsCfg,
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
httpso := util.HTTPSOFromContext(ctx)
waitFuncCtx, done := context.WithTimeout(r.Context(), fwdCfg.waitTimeout)
defer done()
isColdStart, err := waitFunc(
waitFuncCtx,
httpso.GetNamespace(),
httpso.Spec.ScaleTargetRef.Service,
)
if err != nil {
lggr.Error(err, "wait function failed, not forwarding request")
w.WriteHeader(http.StatusBadGateway)
if _, err := w.Write([]byte(fmt.Sprintf("error on backend (%s)", err))); err != nil {
lggr.Error(err, "could not write error response to client")
}
return
}
w.Header().Add("X-KEDA-HTTP-Cold-Start", strconv.FormatBool(isColdStart))
uh := handler.NewUpstream(roundTripper)
uh.ServeHTTP(w, r)
})
}