-
Notifications
You must be signed in to change notification settings - Fork 12
/
pruning_index.go
70 lines (53 loc) · 1.53 KB
/
pruning_index.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
package model
import (
"github.com/iotaledger/hive.go/ierrors"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/runtime/syncutils"
iotago "github.com/iotaledger/iota.go/v4"
)
type PruningIndex struct {
kv kvstore.KVStore
key kvstore.Realm
memLastPrunedEpoch *EvictionIndex[iotago.EpochIndex]
lastPrunedMutex syncutils.RWMutex
}
func NewPruningIndex(kv kvstore.KVStore, key kvstore.Realm) *PruningIndex {
return &PruningIndex{
kv: kv,
key: key,
memLastPrunedEpoch: NewEvictionIndex[iotago.EpochIndex](),
}
}
func (e *PruningIndex) MarkEvicted(epoch iotago.EpochIndex) error {
e.lastPrunedMutex.Lock()
defer e.lastPrunedMutex.Unlock()
e.memLastPrunedEpoch.MarkEvicted(epoch)
return e.kv.Set(e.key, epoch.MustBytes())
}
func (e *PruningIndex) Index() (currentEpoch iotago.EpochIndex, valid bool) {
e.lastPrunedMutex.RLock()
defer e.lastPrunedMutex.RUnlock()
return e.memLastPrunedEpoch.Index()
}
func (e *PruningIndex) NextIndex() iotago.EpochIndex {
e.lastPrunedMutex.RLock()
defer e.lastPrunedMutex.RUnlock()
return e.memLastPrunedEpoch.NextIndex()
}
func (e *PruningIndex) RestoreFromDisk() error {
e.lastPrunedMutex.Lock()
defer e.lastPrunedMutex.Unlock()
lastPrunedBytes, err := e.kv.Get(e.key)
if err != nil {
if ierrors.Is(err, kvstore.ErrKeyNotFound) {
return nil
}
return err
}
lastPrunedEpoch, _, err := iotago.EpochIndexFromBytes(lastPrunedBytes)
if err != nil {
return err
}
e.memLastPrunedEpoch.MarkEvicted(lastPrunedEpoch)
return nil
}