-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
45 lines (36 loc) · 878 Bytes
/
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
package asset
import (
"context"
"github.com/fox-one/dirtoracle/core"
"github.com/patrickmn/go-cache"
"golang.org/x/sync/singleflight"
)
func Cache(assetz core.AssetService) core.AssetService {
return &cacheAssetz{
AssetService: assetz,
caches: cache.New(cache.NoExpiration, cache.NoExpiration),
sf: &singleflight.Group{},
}
}
type cacheAssetz struct {
core.AssetService
caches *cache.Cache
sf *singleflight.Group
}
func (s *cacheAssetz) ReadAsset(ctx context.Context, id string) (*core.Asset, error) {
v, err, _ := s.sf.Do(id, func() (interface{}, error) {
if v, ok := s.caches.Get(id); ok {
return v, nil
}
asset, err := s.AssetService.ReadAsset(ctx, id)
if err != nil {
return nil, err
}
s.caches.SetDefault(id, asset)
return asset, nil
})
if err != nil {
return nil, err
}
return v.(*core.Asset), nil
}