-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
92 lines (71 loc) · 2.16 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package intransport
import (
"crypto/x509"
"sync"
)
// LockedCachedCertRepresenter - awkwardly named interface for a cached and locked certificate entry.
type LockedCachedCertRepresenter interface {
// Cert is the getter function and will be called on a locked entry.
// A nil value is valid as a return, and signals we need to fetch the certificate.
Cert() *x509.Certificate
// SetCert is the certificate setter function and will be called on a locked entry.
SetCert(cert *x509.Certificate)
// Unlock will be called after fetching and / or setting the value. Once Unlock is called,
// no other calls will be made. For subsequent access, Cacher.LockedCachedCert will be called again.
Unlock()
}
// Cacher - interface for caching x509 entries.
type Cacher interface {
// LockedCachedCert will be called for a key, and this should
// return a locked entry.
LockedCachedCert(key string) LockedCachedCertRepresenter
}
type certCacheEntry struct {
sync.Mutex
cert *x509.Certificate
}
func (cce *certCacheEntry) Cert() *x509.Certificate {
return cce.cert
}
func (cce *certCacheEntry) SetCert(cert *x509.Certificate) {
cce.cert = cert
}
type certCache struct {
sync.Mutex
m map[string]*certCacheEntry
}
// NewMapCache - returns a Cacher implementation based on a go map and mutexes.
func NewMapCache() Cacher {
return &certCache{
m: make(map[string]*certCacheEntry),
}
}
func (cc *certCache) LockedCachedCert(key string) LockedCachedCertRepresenter {
cc.Lock()
cce, ok := cc.m[key]
if ok {
cc.Unlock()
cce.Lock()
return cce
}
// cache miss
cce = &certCacheEntry{}
cce.Lock()
cc.m[key] = cce
cc.Unlock()
return cce
}
type nopCache struct{}
type nopCacheEntry struct{}
// NewNopCache - this returns a nop cache, which can be used to disable caching of certificates.
func NewNopCache() Cacher {
return nopCache{}
}
func (nc nopCache) LockedCachedCert(_ string) LockedCachedCertRepresenter {
return nopCacheEntry{}
}
func (nce nopCacheEntry) LockEntry() {}
func (nce nopCacheEntry) Unlock() {}
func (nce nopCacheEntry) UnlockCacher() {}
func (nce nopCacheEntry) Cert() *x509.Certificate { return nil }
func (nce nopCacheEntry) SetCert(_ *x509.Certificate) {}