github.com/koko1123/flow-go-1@v0.29.6/storage/badger/operation/max.go (about) 1 package operation 2 3 import ( 4 "encoding/binary" 5 "errors" 6 "fmt" 7 8 "github.com/dgraph-io/badger/v3" 9 10 "github.com/koko1123/flow-go-1/storage" 11 ) 12 13 // maxKey is the biggest allowed key size in badger 14 const maxKey = 65000 15 16 // max holds the maximum length of keys in the database; in order to optimize 17 // the end prefix of iteration, we need to know how many `0xff` bytes to add. 18 var max uint32 19 20 // we initialize max to maximum size, to detect if it wasn't set yet 21 func init() { 22 max = maxKey 23 } 24 25 // InitMax retrieves the maximum key length to have it internally in the 26 // package after restarting. 27 // No errors are expected during normal operation. 28 func InitMax(tx *badger.Txn) error { 29 key := makePrefix(codeMax) 30 item, err := tx.Get(key) 31 if errors.Is(err, badger.ErrKeyNotFound) { // just keep zero value as default 32 max = 0 33 return nil 34 } 35 if err != nil { 36 return fmt.Errorf("could not get max: %w", err) 37 } 38 _ = item.Value(func(val []byte) error { 39 max = binary.LittleEndian.Uint32(val) 40 return nil 41 }) 42 return nil 43 } 44 45 // SetMax sets the value for the maximum key length used for efficient iteration. 46 // No errors are expected during normal operation. 47 func SetMax(tx storage.Transaction) error { 48 key := makePrefix(codeMax) 49 val := make([]byte, 4) 50 binary.LittleEndian.PutUint32(val, max) 51 err := tx.Set(key, val) 52 if err != nil { 53 return fmt.Errorf("could not set max: %w", err) 54 } 55 return nil 56 }