-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcococache.go
105 lines (88 loc) · 2.13 KB
/
cococache.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
93
94
95
96
97
98
99
100
101
102
103
104
105
package cococache
import (
"fmt"
"log"
"sync"
)
// A Getter loads data for a key.
type Getter interface {
Get(key string) ([]byte, error)
}
// A GetterFunc implements Getter with a function.
type GetterFunc func(key string) ([]byte, error)
// Get implements Getter interface function
func (f GetterFunc) Get(key string) ([]byte, error) {
return f(key)
}
type CocoCache struct {
//callback function
getter Getter
//cache
mainCache cache
peers PeerPicker
}
var (
mu sync.RWMutex
cocoCache *CocoCache
)
// NewCache create a new instance of Group
func NewCache(cacheBytes int64, getter Getter) *CocoCache {
mu.Lock()
defer mu.Unlock()
cocoCache := &CocoCache{
getter: getter,
mainCache: cache{cacheBytes: cacheBytes},
}
return cocoCache
}
// RegisterPeers registers a PeerPicker for choosing remote peer
func (g *CocoCache) RegisterPeers(peers PeerPicker) {
if g.peers != nil {
panic("RegisterPeerPicker called more than once")
}
g.peers = peers
}
// GetCache returns the named group previously created with NewGroup, or
// nil if there's no such group.
func GetCache() *CocoCache {
return cocoCache
}
func (g *CocoCache) Get(key string) (ByteView, error) {
if key == "" {
return ByteView{}, fmt.Errorf("key is required")
}
if v, ok := g.mainCache.get(key); ok {
return v, nil
}
return g.load(key)
}
func (g *CocoCache) load(key string) (value ByteView, err error) {
if g.peers != nil {
if peer, ok := g.peers.PickPeer(key); ok {
if value, err = g.getFromPeer(peer, key); err == nil {
return value, nil
}
log.Println("[CocoCache] Failed to get from peer", err)
}
}
return g.getLocally(key)
}
func (g *CocoCache) getLocally(key string) (ByteView, error) {
bytes, err := g.getter.Get(key)
if err != nil {
return ByteView{}, err
}
value := ByteView{b: bytes}
g.populateCache(key, value)
return value, nil
}
func (g *CocoCache) getFromPeer(peer PeerGetter, key string) (ByteView, error) {
bytes, err := peer.Get(key)
if err != nil {
return ByteView{}, err
}
return ByteView{b: bytes}, nil
}
func (g *CocoCache) populateCache(key string, value ByteView) {
g.mainCache.set(key, value)
}