Skip to content

Commit

Permalink
Merge PR cosmos#6806: Docs & Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderbez authored and chengwenxi committed Jul 22, 2020
1 parent 5570e72 commit 1107e37
Show file tree
Hide file tree
Showing 22 changed files with 185 additions and 83 deletions.
6 changes: 2 additions & 4 deletions client/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import (
"io"
"os"

codectypes "github.com/cosmos/cosmos-sdk/codec/types"

"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"

tmlite "github.com/tendermint/tendermint/lite"
rpcclient "github.com/tendermint/tendermint/rpc/client"
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
yaml "gopkg.in/yaml.v2"

"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
)
Expand Down
13 changes: 0 additions & 13 deletions client/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"strconv"

"github.com/spf13/cobra"
"github.com/spf13/viper"
tmcli "github.com/tendermint/tendermint/libs/cli"

"github.com/cosmos/cosmos-sdk/crypto/keyring"
Expand Down Expand Up @@ -83,12 +82,6 @@ func AddQueryFlagsToCmd(cmd *cobra.Command) {

cmd.SetErr(cmd.ErrOrStderr())
cmd.SetOut(cmd.OutOrStdout())

// TODO: REMOVE VIPER CALLS!
viper.BindPFlag(FlagTrustNode, cmd.Flags().Lookup(FlagTrustNode))
viper.BindPFlag(FlagUseLedger, cmd.Flags().Lookup(FlagUseLedger))
viper.BindPFlag(FlagNode, cmd.Flags().Lookup(FlagNode))
viper.BindPFlag(FlagKeyringBackend, cmd.Flags().Lookup(FlagKeyringBackend))
}

// AddTxFlagsToCmd adds common flags to a module tx command.
Expand Down Expand Up @@ -118,12 +111,6 @@ func AddTxFlagsToCmd(cmd *cobra.Command) {

cmd.SetErr(cmd.ErrOrStderr())
cmd.SetOut(cmd.OutOrStdout())

// TODO: REMOVE VIPER CALLS!
viper.BindPFlag(FlagTrustNode, cmd.Flags().Lookup(FlagTrustNode))
viper.BindPFlag(FlagUseLedger, cmd.Flags().Lookup(FlagUseLedger))
viper.BindPFlag(FlagNode, cmd.Flags().Lookup(FlagNode))
viper.BindPFlag(FlagKeyringBackend, cmd.Flags().Lookup(FlagKeyringBackend))
}

// AddPaginationFlagsToCmd adds common pagination flags to cmd
Expand Down
116 changes: 116 additions & 0 deletions server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Server

The `server` package is responsible for providing the mechanisms necessary to
start an ABCI Tendermint application and providing the CLI framework necessary
to fully bootstrap an application. The package exposes two core commands, `StartCmd`
and `ExportCmd`.

## Preliminary

The root command of an application typically is constructed with three core
sub-commands, query commands, tx commands, and auxiliary commands such as genesis
utilities, and starting an application binary.

It is vital that the root command of an application set the appropriate `PersistentPreRun(E)`
function so all child commands have access to the server and client contexts.
These contexts are set as their default values initially and maybe modified,
scoped to the command, in their respective `PersistentPreRun(E)` functions. Note,
the `client.Context` is typically pre-populated with "default" values that may be
useful for all commands to inherit and override if necessary.

Example:

```go
var (
rootCmd = &cobra.Command{
Use: "simd",
Short: "simulation app",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
return err
}

return server.InterceptConfigsPreRunHandler(cmd)
},
}

encodingConfig = simapp.MakeEncodingConfig()
initClientCtx = client.Context{}.
WithJSONMarshaler(encodingConfig.Marshaler).
WithTxConfig(encodingConfig.TxConfig).
WithCodec(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(simapp.DefaultNodeHome)
)
```

The `SetCmdClientContextHandler` call reads persistent flags via `ReadPersistentCommandFlags`
which creates a `client.Context` and sets that on the root command's `Context`.

The `InterceptConfigsPreRunHandler` call creates a viper literal, default `server.Context`,
and a logger and sets that on the root command's `Context`. The `server.Context`
will be modified and saved to disk via the internal `interceptConfigs` call, which
either reads or creates a Tendermint configuration based on the home path provided.
In addition, `interceptConfigs` also reads and loads the application configuration,
`app.toml`, and binds that to the `server.Context` viper literal. This is vital
so the application can get access to not only the CLI flags, but also to the
application configuration values provided by this file.

## `StartCmd`

The `StartCmd` accepts an `AppCreator` function which returns an `Application`.
The `AppCreator` is responsible for constructing the application based on the
options provided to it via `AppOptions`. The `AppOptions` interface type defines
a single method, `Get() interface{}`, and is implemented as a [viper](https://github.com/spf13/viper)
literal that exists in the `server.Context`. All the possible options an application
may use and provide to the construction process are defined by the `StartCmd`
and by the application's config file, `app.toml`.

The application can either be started in-process or as an external process. The
former creates a Tendermint service and the latter creates a Tendermint Node.

Under the hood, `StartCmd` will call `GetServerContextFromCmd`, which provides
the command access to a `server.Context`. This context provides access to the
viper literal, the Tendermint config and logger. This allows flags to be bound
the viper literal and passed to the application construction.

Example:

```go
func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts server.AppOptions) server.Application {
var cache sdk.MultiStorePersistentCache

if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
cache = store.NewCommitKVStoreCacheManager()
}

skipUpgradeHeights := make(map[int64]bool)
for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) {
skipUpgradeHeights[int64(h)] = true
}

pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts)
if err != nil {
panic(err)
}

return simapp.NewSimApp(
logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))),
baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))),
baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))),
baseapp.SetInterBlockCache(cache),
baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))),
)
}
```

Note, some of the options provided are exposed via CLI flags in the start command
and some are also allowed to be set in the application's `app.toml`. It is recommend
to use the `cast` package for type safety guarantees and due to the limitations of
CLI flag types.
5 changes: 3 additions & 2 deletions simapp/simd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var (
if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
return err
}

return server.InterceptConfigsPreRunHandler(cmd)
},
}
Expand Down Expand Up @@ -114,7 +115,7 @@ func queryCommand() *cobra.Command {
authcmd.QueryTxCmd(),
)

simapp.ModuleBasics.AddQueryCommands(cmd, initClientCtx)
simapp.ModuleBasics.AddQueryCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")

return cmd
Expand All @@ -141,7 +142,7 @@ func txCommand() *cobra.Command {
flags.LineBreak,
)

simapp.ModuleBasics.AddTxCommands(cmd, initClientCtx)
simapp.ModuleBasics.AddTxCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")

return cmd
Expand Down
48 changes: 24 additions & 24 deletions tests/mocks/types_module_module.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions types/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ type AppModuleBasic interface {

// client functionality
RegisterRESTRoutes(client.Context, *mux.Router)
GetTxCmd(clientCtx client.Context) *cobra.Command
GetQueryCmd(clientCtx client.Context) *cobra.Command
GetTxCmd() *cobra.Command
GetQueryCmd() *cobra.Command
}

// BasicManager is a collection of AppModuleBasic
Expand Down Expand Up @@ -109,9 +109,9 @@ func (bm BasicManager) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Rou
//
// TODO: Remove clientCtx argument.
// REF: https://github.com/cosmos/cosmos-sdk/issues/6571
func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, ctx client.Context) {
func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) {
for _, b := range bm {
if cmd := b.GetTxCmd(ctx); cmd != nil {
if cmd := b.GetTxCmd(); cmd != nil {
rootTxCmd.AddCommand(cmd)
}
}
Expand All @@ -121,9 +121,9 @@ func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, ctx client.Contex
//
// TODO: Remove clientCtx argument.
// REF: https://github.com/cosmos/cosmos-sdk/issues/6571
func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, clientCtx client.Context) {
func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) {
for _, b := range bm {
if cmd := b.GetQueryCmd(clientCtx); cmd != nil {
if cmd := b.GetQueryCmd(); cmd != nil {
rootQueryCmd.AddCommand(cmd)
}
}
Expand Down
8 changes: 4 additions & 4 deletions types/module/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ func TestBasicManager(t *testing.T) {
mockAppModuleBasic1.EXPECT().ValidateGenesis(gomock.Eq(cdc), gomock.Eq(wantDefaultGenesis["mockAppModuleBasic1"])).Times(1).Return(errFoo)
mockAppModuleBasic1.EXPECT().RegisterRESTRoutes(gomock.Eq(client.Context{}), gomock.Eq(&mux.Router{})).Times(1)
mockAppModuleBasic1.EXPECT().RegisterCodec(gomock.Eq(cdc)).Times(1)
mockAppModuleBasic1.EXPECT().GetTxCmd(clientCtx).Times(1).Return(nil)
mockAppModuleBasic1.EXPECT().GetQueryCmd(clientCtx).Times(1).Return(nil)
mockAppModuleBasic1.EXPECT().GetTxCmd().Times(1).Return(nil)
mockAppModuleBasic1.EXPECT().GetQueryCmd().Times(1).Return(nil)

mm := module.NewBasicManager(mockAppModuleBasic1)
require.Equal(t, mm["mockAppModuleBasic1"], mockAppModuleBasic1)
Expand All @@ -53,9 +53,9 @@ func TestBasicManager(t *testing.T) {
mm.RegisterRESTRoutes(client.Context{}, &mux.Router{})

mockCmd := &cobra.Command{Use: "root"}
mm.AddTxCommands(mockCmd, clientCtx)
mm.AddTxCommands(mockCmd)

mm.AddQueryCommands(mockCmd, clientCtx)
mm.AddQueryCommands(mockCmd)

// validate genesis returns nil
require.Nil(t, module.NewBasicManager().ValidateGenesis(cdc, wantDefaultGenesis))
Expand Down
4 changes: 2 additions & 2 deletions x/auth/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Rout
}

// GetTxCmd returns the root tx command for the auth module.
func (AppModuleBasic) GetTxCmd(_ client.Context) *cobra.Command {
func (AppModuleBasic) GetTxCmd() *cobra.Command {
return cli.GetTxCmd()
}

// GetQueryCmd returns the root query command for the auth module.
func (AppModuleBasic) GetQueryCmd(_ client.Context) *cobra.Command {
func (AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}

Expand Down
Loading

0 comments on commit 1107e37

Please sign in to comment.