-
Notifications
You must be signed in to change notification settings - Fork 173
/
caching.go
69 lines (55 loc) · 2.3 KB
/
caching.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
package storagewrappers
import (
"context"
"fmt"
"time"
"github.com/karlseguin/ccache/v3"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
"golang.org/x/sync/singleflight"
"github.com/openfga/openfga/pkg/storage"
)
const ttl = time.Hour * 168
var _ storage.OpenFGADatastore = (*cachedOpenFGADatastore)(nil)
type cachedOpenFGADatastore struct {
storage.OpenFGADatastore
lookupGroup singleflight.Group
cache *ccache.Cache[*openfgav1.AuthorizationModel]
}
// NewCachedOpenFGADatastore returns a wrapper over a datastore that caches up to maxSize
// [*openfgav1.AuthorizationModel] on every call to storage.ReadAuthorizationModel.
// It caches with unlimited TTL because models are immutable. It uses LRU for eviction.
func NewCachedOpenFGADatastore(inner storage.OpenFGADatastore, maxSize int) *cachedOpenFGADatastore {
return &cachedOpenFGADatastore{
OpenFGADatastore: inner,
cache: ccache.New(ccache.Configure[*openfgav1.AuthorizationModel]().MaxSize(int64(maxSize))),
}
}
// ReadAuthorizationModel reads the model corresponding to store and model ID.
func (c *cachedOpenFGADatastore) ReadAuthorizationModel(ctx context.Context, storeID, modelID string) (*openfgav1.AuthorizationModel, error) {
cacheKey := fmt.Sprintf("%s:%s", storeID, modelID)
cachedEntry := c.cache.Get(cacheKey)
if cachedEntry != nil {
return cachedEntry.Value(), nil
}
model, err := c.OpenFGADatastore.ReadAuthorizationModel(ctx, storeID, modelID)
if err != nil {
return nil, err
}
c.cache.Set(cacheKey, model, ttl) // These are immutable, once created, there cannot be edits, therefore they can be cached without ttl.
return model, nil
}
// FindLatestAuthorizationModel see [storage.AuthorizationModelReadBackend].FindLatestAuthorizationModel.
func (c *cachedOpenFGADatastore) FindLatestAuthorizationModel(ctx context.Context, storeID string) (*openfgav1.AuthorizationModel, error) {
v, err, _ := c.lookupGroup.Do(fmt.Sprintf("FindLatestAuthorizationModel:%s", storeID), func() (interface{}, error) {
return c.OpenFGADatastore.FindLatestAuthorizationModel(ctx, storeID)
})
if err != nil {
return nil, err
}
return v.(*openfgav1.AuthorizationModel), nil
}
// Close closes the datastore and cleans up any residual resources.
func (c *cachedOpenFGADatastore) Close() {
c.cache.Stop()
c.OpenFGADatastore.Close()
}