-
Notifications
You must be signed in to change notification settings - Fork 151
/
metadata_memcache.go
56 lines (45 loc) · 1.69 KB
/
metadata_memcache.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
package storage
import (
"github.com/iotaledger/hornet/pkg/model/hornet"
)
type CachedMessageMetadataFunc func(messageID hornet.MessageID) (*CachedMetadata, error)
type MetadataMemcache struct {
cachedMessageMetadataFunc CachedMessageMetadataFunc
cachedMsgMetas map[string]*CachedMetadata
}
// NewMetadataMemcache creates a new NewMetadataMemcache instance.
func NewMetadataMemcache(cachedMessageMetadataFunc CachedMessageMetadataFunc) *MetadataMemcache {
return &MetadataMemcache{
cachedMessageMetadataFunc: cachedMessageMetadataFunc,
cachedMsgMetas: make(map[string]*CachedMetadata),
}
}
// Cleanup releases all the cached objects that have been used.
// This MUST be called by the user at the end.
func (c *MetadataMemcache) Cleanup(forceRelease bool) {
// release all msg metadata at the end
for _, cachedMsgMeta := range c.cachedMsgMetas {
cachedMsgMeta.Release(forceRelease) // meta -1
}
c.cachedMsgMetas = make(map[string]*CachedMetadata)
}
// CachedMessageMetadata returns a cached metadata object.
// meta +1
func (c *MetadataMemcache) CachedMessageMetadata(messageID hornet.MessageID) (*CachedMetadata, error) {
messageIDMapKey := messageID.ToMapKey()
var err error
// load up msg metadata
cachedMsgMeta, exists := c.cachedMsgMetas[messageIDMapKey]
if !exists {
cachedMsgMeta, err = c.cachedMessageMetadataFunc(messageID) // meta +1 (this is the one that gets cleared by "Cleanup")
if err != nil {
return nil, err
}
if cachedMsgMeta == nil {
return nil, nil
}
// add the cachedObject to the map, it will be released by calling "Cleanup" at the end
c.cachedMsgMetas[messageIDMapKey] = cachedMsgMeta
}
return cachedMsgMeta.Retain(), nil // meta +1
}