Skip to content

Commit

Permalink
CNS-381: timerstore: add version to support migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
orenl-lava committed Apr 20, 2023
1 parent df26964 commit fbe2b87
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
21 changes: 21 additions & 0 deletions common/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,33 @@ type TimerStore struct {
callbacks [2]TimerCallback // as per TimerType
}

func TimerVersion() uint64 {
return 1
}

// NewTimerStore returns a new TimerStore object
func NewTimerStore(storeKey sdk.StoreKey, cdc codec.BinaryCodec, prefix string) *TimerStore {
tstore := TimerStore{storeKey: storeKey, cdc: cdc, prefix: prefix}
return &tstore
}

func (tstore *TimerStore) getVersion(ctx sdk.Context) uint64 {
store := prefix.NewStore(ctx.KVStore(tstore.storeKey), types.KeyPrefix(tstore.prefix))

b := store.Get(types.KeyPrefix(types.TimerVersionKey))
if b == nil {
return 1
}

return types.DecodeKey(b)
}

func (tstore *TimerStore) setVersion(ctx sdk.Context, val uint64) {
store := prefix.NewStore(ctx.KVStore(tstore.storeKey), types.KeyPrefix(tstore.prefix))
b := types.EncodeKey(val)
store.Set(types.KeyPrefix(types.TimerVersionKey), b)
}

func (tstore *TimerStore) WithCallbackByBlockHeight(callback func(ctx sdk.Context, data string)) *TimerStore {
tstoreNew := tstore
tstoreNew.callbacks[types.BlockHeight] = callback
Expand Down
37 changes: 37 additions & 0 deletions common/timer_migrate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package common

import (
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
)

func (tstore *TimerStore) prefixForErrors(from uint64) string {
return fmt.Sprintf("TimerStore: migration from version %d", from)
}

var timerMigrators = map[int]func (sdk.Context, *TimerStore) error{
// fill with map entrys like "1: timerMigrate1to2"
}

func (tstore *TimerStore) MigrateVersion(ctx sdk.Context) (err error) {
from := tstore.getVersion(ctx)
to := TimerVersion()

for from < to {
function, ok := timerMigrators[int(from)]
if !ok {
return fmt.Errorf("%s not available", prefixForErrors(from))
}

err = function(ctx, tstore)
if err != nil {
return err
}

from += 1
}

tstore.setVersion(ctx, to)
return nil
}
1 change: 1 addition & 0 deletions common/types/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const (
)

const (
TimerVersionKey = "Entry_Version"
NextTimerPrefix = "Timer_Next_"
TimerPrefix = "Timer_Value_"
)
Expand Down

0 comments on commit fbe2b87

Please sign in to comment.