Skip to content

Commit

Permalink
Merge PR #5452: Pass in sdk.Context to router.Route()
Browse files Browse the repository at this point in the history
  • Loading branch information
sunnya97 authored and alexanderbez committed Jan 4, 2020
1 parent 066dd11 commit 17d639a
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ if the provided arguments are invalid.
* (keys) [\#4941](https://github.com/cosmos/cosmos-sdk/issues/4941) Initializing a new keybase through `NewKeyringFromHomeFlag`, `NewKeyringFromDir`, `NewKeyBaseFromHomeFlag`, `NewKeyBaseFromDir`, or `NewInMemory` functions now accept optional parameters of type `KeybaseOption`. These optional parameters are also added on the keys subcommands functions, which are now public, and allows these options to be set on the commands or ignored to default to previous behavior.
* The option introduced in this PR is `WithKeygenFunc` which allows a custom bytes to key implementation to be defined when keys are created.
* (simapp) [\#5419](https://github.com/cosmos/cosmos-sdk/pull/5419) simapp/helpers.GenTx() now accepts a gas argument.
* (baseapp) [\#5455](https://github.com/cosmos/cosmos-sdk/issues/5455) An `sdk.Context` is passed into the `router.Route()`
function.

### Client Breaking Changes

Expand Down
2 changes: 1 addition & 1 deletion baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode runTxMode) (*s
}

msgRoute := msg.Route()
handler := app.router.Route(msgRoute)
handler := app.router.Route(ctx, msgRoute)
if handler == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized message route: %s; message index: %d", msgRoute, i)
}
Expand Down
65 changes: 65 additions & 0 deletions baseapp/baseapp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io/ioutil"
"os"
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -416,6 +417,9 @@ func TestBaseAppOptionSeal(t *testing.T) {
require.Panics(t, func() {
app.SetFauxMerkleMode()
})
require.Panics(t, func() {
app.SetRouter(NewRouter())
})
}

func TestSetMinGasPrices(t *testing.T) {
Expand Down Expand Up @@ -1443,3 +1447,64 @@ func TestGetMaximumBlockGas(t *testing.T) {
app.setConsensusParams(&abci.ConsensusParams{Block: &abci.BlockParams{MaxGas: -5000000}})
require.Panics(t, func() { app.getMaximumBlockGas() })
}

// NOTE: represents a new custom router for testing purposes of WithRouter()
type testCustomRouter struct {
routes sync.Map
}

func (rtr *testCustomRouter) AddRoute(path string, h sdk.Handler) sdk.Router {
rtr.routes.Store(path, h)
return rtr
}

func (rtr *testCustomRouter) Route(ctx sdk.Context, path string) sdk.Handler {
if v, ok := rtr.routes.Load(path); ok {
if h, ok := v.(sdk.Handler); ok {
return h
}
}
return nil
}

func TestWithRouter(t *testing.T) {
// test increments in the ante
anteKey := []byte("ante-key")
anteOpt := func(bapp *BaseApp) { bapp.SetAnteHandler(anteHandlerTxTest(t, capKey1, anteKey)) }

// test increments in the handler
deliverKey := []byte("deliver-key")
routerOpt := func(bapp *BaseApp) {
bapp.SetRouter(&testCustomRouter{routes: sync.Map{}})
bapp.Router().AddRoute(routeMsgCounter, handlerMsgCounter(t, capKey1, deliverKey))
}

app := setupBaseApp(t, anteOpt, routerOpt)
app.InitChain(abci.RequestInitChain{})

// Create same codec used in txDecoder
codec := codec.New()
registerTestCodec(codec)

nBlocks := 3
txPerHeight := 5

for blockN := 0; blockN < nBlocks; blockN++ {
header := abci.Header{Height: int64(blockN) + 1}
app.BeginBlock(abci.RequestBeginBlock{Header: header})

for i := 0; i < txPerHeight; i++ {
counter := int64(blockN*txPerHeight + i)
tx := newTxCounter(counter, counter)

txBytes, err := codec.MarshalBinaryLengthPrefixed(tx)
require.NoError(t, err)

res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
require.True(t, res.IsOK(), fmt.Sprintf("%v", res))
}

app.EndBlock(abci.RequestEndBlock{})
app.Commit()
}
}
8 changes: 8 additions & 0 deletions baseapp/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,11 @@ func (app *BaseApp) SetStoreLoader(loader StoreLoader) {
}
app.storeLoader = loader
}

// SetRouter allows us to customize the router.
func (app *BaseApp) SetRouter(router sdk.Router) {
if app.sealed {
panic("SetRouter() on sealed BaseApp")
}
app.router = router
}
2 changes: 1 addition & 1 deletion baseapp/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ func (rtr *Router) AddRoute(path string, h sdk.Handler) sdk.Router {
// Route returns a handler for a given route path.
//
// TODO: Handle expressive matches.
func (rtr *Router) Route(path string) sdk.Handler {
func (rtr *Router) Route(_ sdk.Context, path string) sdk.Handler {
return rtr.routes[path]
}
2 changes: 1 addition & 1 deletion baseapp/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestRouter(t *testing.T) {
})

rtr.AddRoute("testRoute", testHandler)
h := rtr.Route("testRoute")
h := rtr.Route(sdk.Context{}, "testRoute")
require.NotNil(t, h)

// require panic on duplicate route
Expand Down
4 changes: 2 additions & 2 deletions docs/core/baseapp.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,9 @@ When messages and queries are received by the application, they must be routed t

### Message Routing

[`Message`s](#../building-modules/messages-and-queries.md#messages) need to be routed after they are extracted from transactions, which are sent from the underlying Tendermint engine via the [`CheckTx`](#checktx) and [`DeliverTx`](#delivertx) ABCI messages. To do so, `baseapp` holds a `router` which maps `paths` (`string`) to the appropriate module [`handler`](../building-modules/handler.md). Usually, the `path` is the name of the module.
[`Message`s](#../building-modules/messages-and-queries.md#messages) need to be routed after they are extracted from transactions, which are sent from the underlying Tendermint engine via the [`CheckTx`](#checktx) and [`DeliverTx`](#delivertx) ABCI messages. To do so, `baseapp` holds a `router` which maps `paths` (`string`) to the appropriate module [`handler`](../building-modules/handler.md) using the `.Route(ctx sdk.Context, path string)` function. Usually, the `path` is the name of the module.

+++ https://github.com/cosmos/cosmos-sdk/blob/master/baseapp/router.go
The [default router included in baseapp](https://github.com/cosmos/cosmos-sdk/blob/master/baseapp/router.go) is stateless. However, some applications may want to make use of more stateful routing mechanisms such as allowing governance to disable certain routes or point them to new modules for upgrade purposes. For this reason, the `sdk.Context` is also passed into the `Route` function of the [Router interface](https://github.com/cosmos/cosmos-sdk/blob/master/types/router.go#L12). For a stateless router that doesn't want to make use of this, can just ignore the ctx.

The application's `router` is initilalized with all the routes using the application's [module manager](../building-modules/module-manager.md#manager), which itself is initialized with all the application's modules in the application's [constructor](../basics/app-anatomy.md#app-constructor).

Expand Down
2 changes: 1 addition & 1 deletion types/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ var IsAlphaNumeric = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString
// Router provides handlers for each transaction type.
type Router interface {
AddRoute(r string, h Handler) Router
Route(path string) Handler
Route(ctx Context, path string) Handler
}

// QueryRouter provides queryables for each query path.
Expand Down

0 comments on commit 17d639a

Please sign in to comment.