-
Notifications
You must be signed in to change notification settings - Fork 361
/
cache.go
79 lines (65 loc) · 2.19 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
package auth
import (
"time"
"github.com/treeverse/lakefs/pkg/auth/model"
"github.com/treeverse/lakefs/pkg/cache"
)
type CredentialSetFn func() (*model.Credential, error)
type UserSetFn func() (*model.User, error)
type UserPoliciesSetFn func() ([]*model.Policy, error)
type userKey struct {
id string
username string
externalID string
email string
}
type Cache interface {
GetCredential(accessKeyID string, setFn CredentialSetFn) (*model.Credential, error)
GetUser(key userKey, setFn UserSetFn) (*model.User, error)
GetUserPolicies(userID string, setFn UserPoliciesSetFn) ([]*model.Policy, error)
}
type LRUCache struct {
credentialsCache cache.Cache
userCache cache.Cache
policyCache cache.Cache
}
func NewLRUCache(size int, expiry, jitter time.Duration) *LRUCache {
jitterFn := cache.NewJitterFn(jitter)
return &LRUCache{
credentialsCache: cache.NewCache(size, expiry, jitterFn),
userCache: cache.NewCache(size, expiry, jitterFn),
policyCache: cache.NewCache(size, expiry, jitterFn),
}
}
func (c *LRUCache) GetCredential(accessKeyID string, setFn CredentialSetFn) (*model.Credential, error) {
v, err := c.credentialsCache.GetOrSet(accessKeyID, func() (interface{}, error) { return setFn() })
if err != nil {
return nil, err
}
return v.(*model.Credential), nil
}
func (c *LRUCache) GetUser(key userKey, setFn UserSetFn) (*model.User, error) {
v, err := c.userCache.GetOrSet(key, func() (interface{}, error) { return setFn() })
if err != nil {
return nil, err
}
return v.(*model.User), nil
}
func (c *LRUCache) GetUserPolicies(userID string, setFn UserPoliciesSetFn) ([]*model.Policy, error) {
v, err := c.policyCache.GetOrSet(userID, func() (interface{}, error) { return setFn() })
if err != nil {
return nil, err
}
return v.([]*model.Policy), nil
}
// DummyCache dummy cache that doesn't cache
type DummyCache struct{}
func (d *DummyCache) GetCredential(_ string, setFn CredentialSetFn) (*model.Credential, error) {
return setFn()
}
func (d *DummyCache) GetUser(_ userKey, setFn UserSetFn) (*model.User, error) {
return setFn()
}
func (d *DummyCache) GetUserPolicies(_ string, setFn UserPoliciesSetFn) ([]*model.Policy, error) {
return setFn()
}