-
Notifications
You must be signed in to change notification settings - Fork 179
/
derived_chain_data.go
91 lines (73 loc) · 2.02 KB
/
derived_chain_data.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
package derived
import (
"fmt"
"sync"
"github.com/hashicorp/golang-lru/simplelru"
"github.com/onflow/flow-go/model/flow"
)
const DefaultDerivedDataCacheSize = 1000
// DerivedChainData is a cache of DerivedBlockData databases used for speeding up
// cadence execution.
//
// Since programs are derived from external source, the DerivedBlockData databases
// need not be durable and can be recreated on the fly.
type DerivedChainData struct {
// NOTE: It's unsafe to use RWMutex since lru updates the data structure
// on Get.
mutex sync.Mutex
lru *simplelru.LRU
}
func NewDerivedChainData(chainCacheSize uint) (*DerivedChainData, error) {
lru, err := simplelru.NewLRU(int(chainCacheSize), nil)
if err != nil {
return nil, fmt.Errorf("cannot create LRU cache: %w", err)
}
return &DerivedChainData{
lru: lru,
}, nil
}
func (chain *DerivedChainData) unsafeGet(
currentBlockId flow.Identifier,
) *DerivedBlockData {
currentEntry, ok := chain.lru.Get(currentBlockId)
if ok {
return currentEntry.(*DerivedBlockData)
}
return nil
}
func (chain *DerivedChainData) Get(
currentBlockId flow.Identifier,
) *DerivedBlockData {
chain.mutex.Lock()
defer chain.mutex.Unlock()
return chain.unsafeGet(currentBlockId)
}
func (chain *DerivedChainData) GetOrCreateDerivedBlockData(
currentBlockId flow.Identifier,
parentBlockId flow.Identifier,
) *DerivedBlockData {
chain.mutex.Lock()
defer chain.mutex.Unlock()
currentEntry := chain.unsafeGet(currentBlockId)
if currentEntry != nil {
return currentEntry
}
var current *DerivedBlockData
parentEntry, ok := chain.lru.Get(parentBlockId)
if ok {
current = parentEntry.(*DerivedBlockData).NewChildDerivedBlockData()
} else {
current = NewEmptyDerivedBlockData()
}
chain.lru.Add(currentBlockId, current)
return current
}
func (chain *DerivedChainData) NewDerivedBlockDataForScript(
currentBlockId flow.Identifier,
) *DerivedBlockData {
block := chain.Get(currentBlockId)
if block != nil {
return block.NewChildDerivedBlockData()
}
return NewEmptyDerivedBlockData()
}