@@ -19,7 +19,6 @@ package encoder
1919import (
2020 "sync"
2121
22- cmap "github.com/orcaman/concurrent-map/v2"
2322 "google.golang.org/protobuf/proto"
2423
2524 "github.com/deepflowio/deepflow/message/controller"
@@ -31,27 +30,48 @@ type labelValue struct {
3130 org * common.ORG
3231 lock sync.Mutex
3332 resourceType string
34- strToID cmap. ConcurrentMap [string , int ]
33+ strToID map [string ] int
3534}
3635
3736func newLabelValue (org * common.ORG ) * labelValue {
3837 return & labelValue {
3938 org : org ,
4039 resourceType : "label_value" ,
41- strToID : cmap . New [ int ]( ),
40+ strToID : make ( map [ string ] int ),
4241 }
4342}
4443
4544func (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).
48+ lv .lock .Lock ()
49+ preKeys := make (map [string ]struct {}, len (lv .strToID ))
50+ for k := range lv .strToID {
51+ preKeys [k ] = struct {}{}
52+ }
53+ lv .lock .Unlock ()
54+
4655 var items []* metadbmodel.PrometheusLabelValue
47- err := lv .org .DB .Unscoped ().Find (& items ).Error
48- if err != nil {
56+ if err := lv .org .DB .Select ("id" , "value" ).Find (& items ).Error ; err != nil {
4957 log .Errorf ("db query %s failed: %v" , lv .resourceType , err , lv .org .LogPrefix )
5058 return err
5159 }
60+ newMap := make (map [string ]int , len (items ))
5261 for _ , item := range items {
53- lv . store ( item )
62+ newMap [ item . Value ] = item . ID
5463 }
64+
65+ lv .lock .Lock ()
66+ for k , v := range lv .strToID {
67+ if _ , wasInSnapshot := preKeys [k ]; ! wasInSnapshot {
68+ // Written by encode() after the snapshot; may not be in the DB
69+ // snapshot yet, so preserve it to avoid a spurious cache miss.
70+ newMap [k ] = v
71+ }
72+ }
73+ lv .strToID = newMap
74+ lv .lock .Unlock ()
5575 return nil
5676}
5777
@@ -86,12 +106,10 @@ func (lv *labelValue) encode(strs []string) ([]*controller.PrometheusLabelValue,
86106}
87107
88108func (lv * labelValue ) getID (str string ) (int , bool ) {
89- if item , ok := lv .strToID .Get (str ); ok {
90- return item , true
91- }
92- return 0 , false
109+ id , ok := lv .strToID [str ]
110+ return id , ok
93111}
94112
95113func (lv * labelValue ) store (item * metadbmodel.PrometheusLabelValue ) {
96- lv .strToID . Set ( item .Value , item .ID )
114+ lv .strToID [ item .Value ] = item .ID
97115}
0 commit comments