Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CNS-381: timerstore: add version to support migrations #416

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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