forked from kyma-project/kyma
/
cache.go
73 lines (56 loc) · 2.06 KB
/
cache.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
package proxy
import (
"net/http"
"net/http/httputil"
"time"
"github.com/kyma-project/kyma/components/application-gateway/internal/apperrors"
"github.com/kyma-project/kyma/components/application-gateway/internal/authorization"
"github.com/kyma-project/kyma/components/application-gateway/internal/csrf"
gocache "github.com/patrickmn/go-cache"
)
const cleanupInterval = 60
type CacheEntry struct {
Proxy *httputil.ReverseProxy
AuthorizationStrategy *authorizationStrategyWrapper
CSRFTokenStrategy csrf.TokenStrategy
}
type authorizationStrategyWrapper struct {
actualStrategy authorization.Strategy
proxy *httputil.ReverseProxy
}
func (ce *authorizationStrategyWrapper) AddAuthorization(r *http.Request) apperrors.AppError {
ts := func(transport *http.Transport) {
ce.proxy.Transport = transport
}
return ce.actualStrategy.AddAuthorization(r, ts)
}
func (ce *authorizationStrategyWrapper) Invalidate() {
ce.actualStrategy.Invalidate()
}
type Cache interface {
// Get returns entry from the cache
Get(id string) (*CacheEntry, bool)
// Put adds entry to the cache
Put(id string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy, csrfTokenStrategy csrf.TokenStrategy) *CacheEntry
}
type cache struct {
proxyCache *gocache.Cache
}
// NewCache creates new cache with specified TTL
func NewCache(proxyCacheTTL int) Cache {
return &cache{
proxyCache: gocache.New(time.Duration(proxyCacheTTL)*time.Second, cleanupInterval*time.Second),
}
}
func (p *cache) Get(id string) (*CacheEntry, bool) {
proxy, found := p.proxyCache.Get(id)
if !found {
return nil, false
}
return proxy.(*CacheEntry), found
}
func (p *cache) Put(id string, reverseProxy *httputil.ReverseProxy, authorizationStrategy authorization.Strategy, csrfTokenStrategy csrf.TokenStrategy) *CacheEntry {
proxy := &CacheEntry{Proxy: reverseProxy, AuthorizationStrategy: &authorizationStrategyWrapper{authorizationStrategy, reverseProxy}, CSRFTokenStrategy: csrfTokenStrategy}
p.proxyCache.Set(id, proxy, gocache.DefaultExpiration)
return proxy
}