-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
60 lines (52 loc) · 1.14 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
package cassette
import (
"time"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/peer"
)
type (
cache struct {
c *Cassette
cache *lru.TwoQueueCache[string, cacheRecord]
}
cacheRecord struct {
insertedAt time.Time
providers []peer.AddrInfo
//TODO: optimize cache memory consumption by deduplication of addrinfos.
}
)
func newCache(c *Cassette) (*cache, error) {
twoq, err := lru.New2Q[string, cacheRecord](c.cacheSize)
if err != nil {
return nil, err
}
return &cache{
c: c,
cache: twoq,
}, nil
}
func (l *cache) getProviders(c cid.Cid) ([]peer.AddrInfo, bool) {
value, ok := l.cache.Get(string(c.Hash()))
switch {
case !ok:
return nil, false
case time.Since(value.insertedAt) > l.c.cacheExpiry:
l.expire(c)
return nil, false
default:
return value.providers, true
}
}
func (l *cache) putProviders(c cid.Cid, providers []peer.AddrInfo) {
l.cache.Add(string(c.Hash()), cacheRecord{
insertedAt: time.Now(),
providers: providers,
})
}
func (l *cache) expire(c cid.Cid) {
l.cache.Remove(string(c.Hash()))
}
func (l *cache) len() int {
return l.cache.Len()
}