github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/wasm/watcher/write.go (about) 1 package watcher 2 3 import ( 4 "log" 5 6 sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types" 7 ) 8 9 func NewHeight() { 10 if Enable() && len(blockStateCache) != 0 { 11 blockStateCache = make(map[string]*WatchMessage) 12 } 13 } 14 15 func Save(err error) { 16 if !Enable() { 17 return 18 } 19 txCacheMtx.Lock() 20 if err == nil { 21 for _, msg := range txStateCache { 22 blockStateCache[string(msg.Key)] = msg 23 } 24 } 25 txStateCache = txStateCache[:0] 26 txCacheMtx.Unlock() 27 } 28 29 func Commit() { 30 if !Enable() { 31 return 32 } 33 if len(blockStateCache) == 0 { 34 return 35 } 36 blockStateCacheCopy := blockStateCache 37 task := func() { 38 batch := db.NewBatch() 39 for _, msg := range blockStateCacheCopy { 40 if msg.IsDelete { 41 batch.Delete(msg.Key) 42 } else { 43 batch.Set(msg.Key, msg.Value) 44 } 45 } 46 if err := batch.Write(); err != nil { 47 log.Println("wasm watchDB batch write error:", err.Error()) 48 } 49 } 50 tasks <- task 51 } 52 53 var tasks = make(chan func(), 5*3) 54 55 func taskRoutine() { 56 for task := range tasks { 57 task() 58 } 59 } 60 61 type writeKVStore struct { 62 sdk.KVStore 63 } 64 65 func WrapWriteKVStore(store sdk.KVStore) sdk.KVStore { 66 if !Enable() { 67 return store 68 } 69 70 return &writeKVStore{ 71 KVStore: store, 72 } 73 } 74 75 func (w *writeKVStore) Set(key, value []byte) { 76 w.KVStore.Set(key, value) 77 txStateCache = append(txStateCache, &WatchMessage{Key: key, Value: value}) 78 } 79 80 func (w *writeKVStore) Delete(key []byte) { 81 w.KVStore.Delete(key) 82 txStateCache = append(txStateCache, &WatchMessage{Key: key, IsDelete: true}) 83 }