Skip to content

Commit

Permalink
refactor: debug CLI helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanchriswhite committed Jun 6, 2023
1 parent 9dc7949 commit 81e15f6
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 97 deletions.
103 changes: 15 additions & 88 deletions app/client/cli/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,18 @@ import (
"os"

"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/anypb"

"github.com/pokt-network/pocket/app/client/cli/helpers"
"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/p2p"
"github.com/pokt-network/pocket/p2p/providers/current_height_provider"
rpcCHP "github.com/pokt-network/pocket/p2p/providers/current_height_provider/rpc"
"github.com/pokt-network/pocket/p2p/providers/peerstore_provider"
rpcABP "github.com/pokt-network/pocket/p2p/providers/peerstore_provider/rpc"
typesP2P "github.com/pokt-network/pocket/p2p/types"
"github.com/pokt-network/pocket/runtime"
"github.com/pokt-network/pocket/runtime/defaults"
"github.com/pokt-network/pocket/shared/messaging"
"github.com/pokt-network/pocket/shared/modules"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/anypb"
)

// TECHDEBT: Lowercase variables / constants that do not need to be exported.
Expand All @@ -33,9 +32,6 @@ const (
)

var (
// A P2P module is initialized in order to broadcast a message to the local network
p2pMod modules.P2PModule

items = []string{
PromptPrintNodeState,
PromptTriggerNextView,
Expand All @@ -45,16 +41,8 @@ var (
PromptSendMetadataRequest,
PromptSendBlockRequest,
}

genesisPath string = runtime.GetEnv("GENESIS_PATH", "build/config/genesis.json")
rpcHost string
)

// NOTE: this is required by the linter, otherwise a simple string constant would have been enough
type cliContextKey string

const busCLICtxKey = "bus"

func init() {
dbg := NewDebugCommand()
dbg.AddCommand(NewDebugSubCommands()...)
Expand All @@ -66,7 +54,7 @@ func init() {
validator1Endpoint = defaults.Validator1EndpointK8S
}

rpcHost = runtime.GetEnv("RPC_HOST", validator1Endpoint)
helpers.RpcHost = runtime.GetEnv("RPC_HOST", validator1Endpoint)
}

// NewDebugSubCommands builds out the list of debug subcommands by matching the
Expand All @@ -77,10 +65,8 @@ func NewDebugSubCommands() []*cobra.Command {
commands := make([]*cobra.Command, len(items))
for idx, promptItem := range items {
commands[idx] = &cobra.Command{
Use: promptItem,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
persistentPreRun(cmd, args)
},
Use: promptItem,
PersistentPreRunE: helpers.P2PDependenciesPreRunE,
Run: func(cmd *cobra.Command, args []string) {
handleSelect(cmd, cmd.Use)
},
Expand All @@ -93,70 +79,11 @@ func NewDebugSubCommands() []*cobra.Command {
// NewDebugCommand returns the cobra CLI for the Debug command.
func NewDebugCommand() *cobra.Command {
return &cobra.Command{
Use: "debug",
Short: "Debug utility for rapid development",
Args: cobra.MaximumNArgs(0),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
persistentPreRun(cmd, args)
},
RunE: runDebug,
}
}

// persistentPreRun is called by both debug and debug sub-commands before runs
func persistentPreRun(cmd *cobra.Command, _ []string) {
// TECHDEBT: this is to keep backwards compatibility with localnet
configPath = runtime.GetEnv("CONFIG_PATH", "build/config/config1.json")
rpcURL := fmt.Sprintf("http://%s:%s", rpcHost, defaults.DefaultRPCPort)

runtimeMgr := runtime.NewManagerFromFiles(
configPath, genesisPath,
runtime.WithClientDebugMode(),
runtime.WithRandomPK(),
)

bus := runtimeMgr.GetBus()
setValueInCLIContext(cmd, busCLICtxKey, bus)

setupPeerstoreProvider(*runtimeMgr, rpcURL)
setupCurrentHeightProvider(*runtimeMgr, rpcURL)
setupAndStartP2PModule(*runtimeMgr)
}

func setupPeerstoreProvider(rm runtime.Manager, rpcURL string) {
bus := rm.GetBus()
modulesRegistry := bus.GetModulesRegistry()
pstoreProvider := rpcABP.NewRPCPeerstoreProvider(
rpcABP.WithP2PConfig(rm.GetConfig().P2P),
rpcABP.WithCustomRPCURL(rpcURL),
)
modulesRegistry.RegisterModule(pstoreProvider)
}

func setupCurrentHeightProvider(rm runtime.Manager, rpcURL string) {
bus := rm.GetBus()
modulesRegistry := bus.GetModulesRegistry()
currentHeightProvider := rpcCHP.NewRPCCurrentHeightProvider(
rpcCHP.WithCustomRPCURL(rpcURL),
)
modulesRegistry.RegisterModule(currentHeightProvider)
}

func setupAndStartP2PModule(rm runtime.Manager) {
bus := rm.GetBus()
mod, err := p2p.Create(bus)
if err != nil {
logger.Global.Fatal().Err(err).Msg("Failed to create p2p module")
}

var ok bool
p2pMod, ok = mod.(modules.P2PModule)
if !ok {
logger.Global.Fatal().Msgf("unexpected P2P module type: %T", mod)
}

if err := p2pMod.Start(); err != nil {
logger.Global.Fatal().Err(err).Msg("Failed to start p2p module")
Use: "debug",
Short: "Debug utility for rapid development",
Args: cobra.MaximumNArgs(0),
PersistentPreRunE: helpers.P2PDependenciesPreRunE,
RunE: runDebug,
}
}

Expand Down Expand Up @@ -269,7 +196,7 @@ func broadcastDebugMessage(cmd *cobra.Command, debugMsg *messaging.DebugMessage)
if err != nil {
logger.Global.Fatal().Err(err).Msg("Failed to convert validator address into pocketCrypto.Address")
}
if err := p2pMod.Send(addr, anyProto); err != nil {
if err := helpers.P2PMod.Send(addr, anyProto); err != nil {
logger.Global.Error().Err(err).Msg("Failed to send debug message")
}
}
Expand Down Expand Up @@ -299,14 +226,14 @@ func sendDebugMessage(cmd *cobra.Command, debugMsg *messaging.DebugMessage) {
logger.Global.Fatal().Err(err).Msg("Failed to convert validator address into pocketCrypto.Address")
}

if err := p2pMod.Send(validatorAddress, anyProto); err != nil {
if err := helpers.P2PMod.Send(validatorAddress, anyProto); err != nil {
logger.Global.Error().Err(err).Msg("Failed to send debug message")
}
}

// fetchPeerstore retrieves the providers from the CLI context and uses them to retrieve the address book for the current height
func fetchPeerstore(cmd *cobra.Command) (typesP2P.Peerstore, error) {
bus, ok := getValueFromCLIContext[modules.Bus](cmd, busCLICtxKey)
bus, ok := helpers.GetValueFromCLIContext[modules.Bus](cmd, helpers.BusCLICtxKey)
if !ok || bus == nil {
return nil, errors.New("retrieving bus from CLI context")
}
Expand Down
14 changes: 14 additions & 0 deletions app/client/cli/helpers/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package helpers

import (
"github.com/pokt-network/pocket/runtime"
"github.com/pokt-network/pocket/shared/modules"
)

var (
GenesisPath = runtime.GetEnv("GENESIS_PATH", "build/config/genesis.json")
RpcHost string

//P2PMod is initialized in order to broadcast a message to the local network
P2PMod modules.P2PModule
)
20 changes: 20 additions & 0 deletions app/client/cli/helpers/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package helpers

import (
"context"
"github.com/spf13/cobra"
)

const BusCLICtxKey cliContextKey = "bus"

// NOTE: this is required by the linter, otherwise a simple string constant would have been enough
type cliContextKey string

func SetValueInCLIContext(cmd *cobra.Command, key cliContextKey, value any) {
cmd.SetContext(context.WithValue(cmd.Context(), key, value))
}

func GetValueFromCLIContext[T any](cmd *cobra.Command, key cliContextKey) (T, bool) {
value, ok := cmd.Context().Value(key).(T)
return value, ok
}
75 changes: 75 additions & 0 deletions app/client/cli/helpers/setup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package helpers

import (
"fmt"
"github.com/pokt-network/pocket/app/client/cli/flags"
"github.com/spf13/cobra"

"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/p2p"
rpc2 "github.com/pokt-network/pocket/p2p/providers/current_height_provider/rpc"
"github.com/pokt-network/pocket/p2p/providers/peerstore_provider/rpc"
"github.com/pokt-network/pocket/runtime"
"github.com/pokt-network/pocket/runtime/defaults"
"github.com/pokt-network/pocket/shared/modules"
)

// P2PDependenciesPreRunE initializes peerstore & current height providers, and a
// p2p module with consumes them. Everything is registered to the bus.
func P2PDependenciesPreRunE(cmd *cobra.Command, _ []string) error {
// TECHDEBT: this is to keep backwards compatibility with localnet
flags.ConfigPath = runtime.GetEnv("CONFIG_PATH", "build/config/config1.json")
rpcURL := fmt.Sprintf("http://%s:%s", RpcHost, defaults.DefaultRPCPort)

runtimeMgr := runtime.NewManagerFromFiles(
flags.ConfigPath, GenesisPath,
runtime.WithClientDebugMode(),
runtime.WithRandomPK(),
)

bus := runtimeMgr.GetBus()
SetValueInCLIContext(cmd, BusCLICtxKey, bus)

setupPeerstoreProvider(*runtimeMgr, rpcURL)
setupCurrentHeightProvider(*runtimeMgr, rpcURL)
setupAndStartP2PModule(*runtimeMgr)

return nil
}

func setupPeerstoreProvider(rm runtime.Manager, rpcURL string) {
bus := rm.GetBus()
modulesRegistry := bus.GetModulesRegistry()
pstoreProvider := rpc.NewRPCPeerstoreProvider(
rpc.WithP2PConfig(rm.GetConfig().P2P),
rpc.WithCustomRPCURL(rpcURL),
)
modulesRegistry.RegisterModule(pstoreProvider)
}

func setupCurrentHeightProvider(rm runtime.Manager, rpcURL string) {
bus := rm.GetBus()
modulesRegistry := bus.GetModulesRegistry()
currentHeightProvider := rpc2.NewRPCCurrentHeightProvider(
rpc2.WithCustomRPCURL(rpcURL),
)
modulesRegistry.RegisterModule(currentHeightProvider)
}

func setupAndStartP2PModule(rm runtime.Manager) {
bus := rm.GetBus()
mod, err := p2p.Create(bus)
if err != nil {
logger.Global.Fatal().Err(err).Msg("Failed to create p2p module")
}

var ok bool
P2PMod, ok = mod.(modules.P2PModule)
if !ok {
logger.Global.Fatal().Msgf("unexpected P2P module type: %T", mod)
}

if err := P2PMod.Start(); err != nil {
logger.Global.Fatal().Err(err).Msg("Failed to start p2p module")
}
}
9 changes: 0 additions & 9 deletions app/client/cli/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,15 +326,6 @@ func boldText[T string | []byte](s T) string {
return fmt.Sprintf("\033[1m%s\033[0m", s)
}

func setValueInCLIContext(cmd *cobra.Command, key cliContextKey, value any) {
cmd.SetContext(context.WithValue(cmd.Context(), key, value))
}

func getValueFromCLIContext[T any](cmd *cobra.Command, key cliContextKey) (T, bool) {
value, ok := cmd.Context().Value(key).(T)
return value, ok
}

// confirmPassphrase should be used when a new key is being created or a raw unarmored key is being imported
func confirmPassphrase(currPwd string) {
confirm := readPassphraseMessage("", "Confirm passphrase: ")
Expand Down

0 comments on commit 81e15f6

Please sign in to comment.