-
Notifications
You must be signed in to change notification settings - Fork 671
/
status_state.go
93 lines (77 loc) · 2.33 KB
/
status_state.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package avax
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/cache/metercacher"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/choices"
)
const (
statusCacheSize = 8192
)
// StatusState is a thin wrapper around a database to provide, caching,
// serialization, and de-serialization for statuses.
type StatusState interface {
// Status returns a status from storage.
GetStatus(id ids.ID) (choices.Status, error)
// PutStatus saves a status in storage.
PutStatus(id ids.ID, status choices.Status) error
// DeleteStatus removes a status from storage.
DeleteStatus(id ids.ID) error
}
type statusState struct {
// ID -> Status of thing with that ID, or nil if StatusState doesn't have
// that status.
statusCache cache.Cacher
statusDB database.Database
}
func NewStatusState(db database.Database) StatusState {
return &statusState{
statusCache: &cache.LRU{Size: statusCacheSize},
statusDB: db,
}
}
func NewMeteredStatusState(db database.Database, metrics prometheus.Registerer) (StatusState, error) {
cache, err := metercacher.New(
"status_cache",
metrics,
&cache.LRU{Size: statusCacheSize},
)
return &statusState{
statusCache: cache,
statusDB: db,
}, err
}
func (s *statusState) GetStatus(id ids.ID) (choices.Status, error) {
if statusIntf, found := s.statusCache.Get(id); found {
if statusIntf == nil {
return choices.Unknown, database.ErrNotFound
}
return statusIntf.(choices.Status), nil
}
val, err := database.GetUInt32(s.statusDB, id[:])
if err == database.ErrNotFound {
s.statusCache.Put(id, nil)
return choices.Unknown, database.ErrNotFound
}
if err != nil {
return choices.Unknown, err
}
status := choices.Status(val)
if err := status.Valid(); err != nil {
return choices.Unknown, err
}
s.statusCache.Put(id, status)
return status, nil
}
func (s *statusState) PutStatus(id ids.ID, status choices.Status) error {
s.statusCache.Put(id, status)
return database.PutUInt32(s.statusDB, id[:], uint32(status))
}
func (s *statusState) DeleteStatus(id ids.ID) error {
s.statusCache.Put(id, nil)
return s.statusDB.Delete(id[:])
}