@@ -31,6 +31,9 @@ type labelValue struct {
3131 lock sync.Mutex
3232 resourceType string
3333 strToID map [string ]int
34+
35+ isRefreshing bool
36+ pendingKeys map [string ]int
3437}
3538
3639func newLabelValue (org * common.ORG ) * labelValue {
@@ -41,16 +44,29 @@ func newLabelValue(org *common.ORG) *labelValue {
4144 }
4245}
4346
44- func (lv * labelValue ) refresh (args ... interface {}) error {
45- // Snapshot existing keys before querying DB, to identify entries added
46- // by encode() during the query window (those must be preserved even if
47- // not yet visible in the DB snapshot).
47+ func (lv * labelValue ) MarkRefresh () {
4848 lv .lock .Lock ()
49- preKeys := make (map [string ]struct {}, len (lv .strToID ))
50- for k := range lv .strToID {
51- preKeys [k ] = struct {}{}
49+ defer lv .lock .Unlock ()
50+ lv .isRefreshing = true
51+ lv .pendingKeys = make (map [string ]int )
52+ }
53+
54+ func (lv * labelValue ) MarkRefreshDone () {
55+ lv .lock .Lock ()
56+ defer lv .lock .Unlock ()
57+ lv .isRefreshing = false
58+ lv .pendingKeys = nil
59+ }
60+
61+ func (lv * labelValue ) refresh (args ... interface {}) error {
62+ lv .MarkRefresh ()
63+ defer lv .MarkRefreshDone ()
64+
65+ var count int64
66+ if err := lv .org .DB .Model (& metadbmodel.PrometheusLabelValue {}).Count (& count ).Error ; err != nil {
67+ log .Errorf ("db query %s failed: %v" , lv .resourceType , err , lv .org .LogPrefix )
68+ return err
5269 }
53- lv .lock .Unlock ()
5470
5571 rows , err := lv .org .DB .Model (& metadbmodel.PrometheusLabelValue {}).Select ("id" , "value" ).Rows ()
5672 if err != nil {
@@ -59,7 +75,7 @@ func (lv *labelValue) refresh(args ...interface{}) error {
5975 }
6076 defer rows .Close ()
6177
62- newMap := make (map [string ]int )
78+ newMap := make (map [string ]int , count )
6379 for rows .Next () {
6480 var id int
6581 var value string
@@ -75,15 +91,12 @@ func (lv *labelValue) refresh(args ...interface{}) error {
7591 }
7692
7793 lv .lock .Lock ()
78- for k , v := range lv .strToID {
79- if _ , wasInSnapshot := preKeys [k ]; ! wasInSnapshot {
80- // Written by encode() after the snapshot; may not be in the DB
81- // snapshot yet, so preserve it to avoid a spurious cache miss.
82- newMap [k ] = v
83- }
94+ for k , v := range lv .pendingKeys {
95+ newMap [k ] = v
8496 }
8597 lv .strToID = newMap
8698 lv .lock .Unlock ()
99+
87100 return nil
88101}
89102
@@ -124,4 +137,8 @@ func (lv *labelValue) getID(str string) (int, bool) {
124137
125138func (lv * labelValue ) store (item * metadbmodel.PrometheusLabelValue ) {
126139 lv .strToID [item .Value ] = item .ID
140+
141+ if lv .isRefreshing {
142+ lv .pendingKeys [item .Value ] = item .ID
143+ }
127144}
0 commit comments