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

feat(server/v2): add config & start helper #20505

Merged
merged 146 commits into from
Jun 19, 2024
Merged

feat(server/v2): add config & start helper #20505

merged 146 commits into from
Jun 19, 2024

Conversation

hieuvubk
Copy link
Contributor

@hieuvubk hieuvubk commented May 31, 2024

Description

Closes: #19720


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • Refactor

    • Simplified configuration settings by removing unnecessary initialization functions.
    • Updated function calls for better compatibility and removed unused import statements.
    • Changed import paths to align with new module structure.
  • Chores

    • Added TODO comments for future improvements and dependency considerations.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK!

server/v2/server.go Dismissed Show dismissed Hide dismissed
server/v2/commands.go Fixed Show fixed Hide fixed
server/v2/commands.go Fixed Show fixed Hide fixed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Outside diff range and nitpick comments (4)
server/v2/api/grpc/server.go (1)

[!TIP]
Codebase Verification

The rg command confirms that the RegisterGRPCServer function is not called elsewhere in the server/v2/api/grpc/server.go file, except for the commented-out line.

To ensure clarity and maintainability, if the commented-out registration is intentional, it would be beneficial to add a comment explaining why it is disabled.

  • File: server/v2/api/grpc/server.go
  • Lines: 50-61

Consider adding a comment to explain why app.RegisterGRPCServer(grpcSrv) is commented out.

Analysis chain

Line range hint 44-58: This method properly initializes a gRPC server with configurations derived from a Viper instance. It handles potential errors during the unmarshalling of configuration which is good practice. However, it seems like the registration of gRPC services (app.RegisterGRPCServer(grpcSrv)) is commented out. If this is intentional, consider adding a comment explaining why.


The rg command output indicates that the RegisterGRPCServer function is defined and used in various parts of the codebase. However, the specific line in server/v2/api/grpc/server.go where it is commented out suggests that this registration was intended but is currently disabled.

To confirm if this is the only instance where RegisterGRPCServer is intended to be called in server/v2/api/grpc/server.go, we should search for any other occurrences of RegisterGRPCServer in this specific file.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify if the gRPC services are registered elsewhere in the codebase.

# Test: Search for `RegisterGRPCServer` usage. Expect: Find usage in other parts of the codebase.
rg --type go 'RegisterGRPCServer'

Length of output: 872



Script:

#!/bin/bash
# Description: Verify if RegisterGRPCServer is called elsewhere in server/v2/api/grpc/server.go

# Test: Search for RegisterGRPCServer usage in server/v2/api/grpc/server.go. Expect: Find no other instances.
rg 'RegisterGRPCServer' server/v2/api/grpc/server.go

Length of output: 203

server/v2/cometbft/server.go (1)

Line range hint 74-113: The Init method of CometBFTServer sets up the server with necessary configurations and handlers. The method is well-structured and handles different components of the server setup. However, the error handling could be improved by not using panic for handling errors during snapshot store retrieval (line 102). Consider returning the error instead.

- panic(err)
+ return nil, fmt.Errorf("failed to get snapshot store: %w", err)
server/v2/testdata/config.toml (2)

11-11: Ensure the version field is updated if any backward-incompatible changes were made in this version.


24-43: Review the database backend options to ensure all are supported and well-documented. Consider marking experimental options more clearly.

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d014b2 and a53bec5.

Files ignored due to path filters (2)
  • server/v2/cometbft/go.sum is excluded by !**/*.sum
  • server/v2/go.sum is excluded by !**/*.sum
Files selected for processing (16)
  • runtime/v2/app.go (1 hunks)
  • server/v2/api/grpc/server.go (3 hunks)
  • server/v2/cometbft/go.mod (3 hunks)
  • server/v2/cometbft/server.go (7 hunks)
  • server/v2/commands.go (2 hunks)
  • server/v2/go.mod (6 hunks)
  • server/v2/server.go (6 hunks)
  • server/v2/server_mock_test.go (2 hunks)
  • server/v2/server_test.go (3 hunks)
  • server/v2/testdata/config.toml (1 hunks)
  • server/v2/types.go (1 hunks)
  • server/v2/util.go (1 hunks)
  • simapp/v2/app_di.go (2 hunks)
  • simapp/v2/go.mod (2 hunks)
  • simapp/v2/simdv2/cmd/commands.go (6 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (3 hunks)
Files skipped from review due to trivial changes (1)
  • simapp/v2/simdv2/cmd/root_di.go
Additional context used
Path-based instructions (11)
server/v2/types.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server_mock_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/util.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

runtime/v2/app.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/grpc/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/app_di.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/cometbft/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

GitHub Check: gosec
server/v2/commands.go

[warning] 54-54: Errors unhandled.
Errors unhandled.


[warning] 46-46: Errors unhandled.
Errors unhandled.

server/v2/server.go

[failure] 173-173: Expect directory permissions to be 0750 or less
Expect directory permissions to be 0750 or less

Additional comments not posted (28)
server/v2/types.go (3)

9-10: This implementation of GetAppManager correctly returns an AppManager instance parameterized with transaction.Tx, which aligns with the expected transaction management strategy.


11-11: The method GetConsensusAuthority is implemented correctly, providing a straightforward means to retrieve the consensus authority identifier.


12-12: The InterfaceRegistry method correctly returns an interface registry, which is crucial for the application's operation and interface management.

server/v2/server_mock_test.go (1)

57-59: The Init method in the mock server is implemented correctly, accepting necessary parameters for initialization and aligns well with the interface requirements.

server/v2/util.go (4)

15-30: The implementation of SetCmdServerContext properly handles the command context and enriches it with necessary values for logger and Viper, adhering to best practices for context management in commands.


32-39: GetViperFromCmd is implemented to ensure that a Viper instance is always available from the command context, handling null cases by providing a new instance. This is a robust approach to configuration management.


41-49: GetConfigFromViper effectively retrieves and handles configurations, providing fallbacks to default configurations in case of errors. This ensures robustness in configuration management.


51-58: GetLoggerFromCmd correctly retrieves a logger from the command's context, providing a new logger instance when necessary. This ensures that logging capabilities are always maintained.

server/v2/server_test.go (1)

119-133: TestReadConfig is well-implemented, covering the essential aspects of configuration reading and parsing. It ensures that the configuration management functionality is robust and error-free.

runtime/v2/app.go (1)

138-140: Ensure GetAppManager method is necessary and well-documented.

The addition of GetAppManager seems aligned with the need to expose AppManager for external use. Ensure this method is covered by unit tests and properly documented to clarify its usage.

server/v2/go.mod (1)

9-9: Validate new and updated dependencies.

Ensure all new and updated dependencies are compatible and necessary for the project. Verify licenses and perform a security audit to ensure there are no vulnerabilities associated with these dependencies.

Also applies to: 20-21, 47-49, 51-64

server/v2/api/grpc/server.go (1)

Line range hint 100-108: The Start method correctly handles the server startup in a separate goroutine, which is a good practice for non-blocking operations. The error handling and logging are also well implemented.

simapp/v2/simdv2/cmd/commands.go (3)

53-59: The newApp function initializes a new application instance using the simapp.NewSimApp method. It correctly handles the application setup and returns a configured serverv2.App instance. This is a clean and concise implementation.


Line range hint 105-115: The genesisCommand function builds and returns a new genesis-related command. It correctly adds subcommands if provided. This function is well-implemented with clear and concise logic.


Line range hint 135-160: The appExport function handles the export of application state. The error handling is robust, ensuring that all necessary conditions are met before proceeding with the export. This function is well-structured and effectively uses early returns for error handling.

simapp/v2/app_di.go (1)

238-238: The InterfaceRegistry method correctly retrieves the interface registry from the SimApp instance. This method is a straightforward accessor and is implemented correctly.

server/v2/cometbft/server.go (1)

Line range hint 121-160: The Start method handles the server startup and correctly retrieves the configuration from the context. The method is well-implemented, with appropriate error handling and logging. The separation of concerns and clear structuring of the code enhance its readability and maintainability.

server/v2/cometbft/go.mod (2)

10-10: The addition of the cosmossdk.io/log replacement ensures that local changes in the logging functionality are utilized, which is crucial for maintaining consistency during development.


42-42: Updating github.com/spf13/viper to version 1.19.0 is appropriate to leverage the latest features and fixes, especially for enhanced configuration management.

simapp/v2/go.mod (2)

13-13: The addition of cosmossdk.io/server/v2 and cosmossdk.io/server/v2/cometbft as dependencies is crucial for integrating the new server functionalities and aligns well with the objectives of the PR.


49-52: The inclusion of new replace directives for cosmossdk.io/client/v2 and cosmossdk.io/tools/confix ensures that local developments are utilized, facilitating testing and integration before final deployment.

server/v2/testdata/config.toml (7)

200-213: Review peer connection settings to ensure they align with network security and performance requirements.


103-114: Ensure the grpc_laddr setting is adequately tested, especially since it's left empty by default.


393-411: Validate that consensus timing configurations are correctly used in the consensus algorithm.


344-374: Ensure that state sync settings are correctly implemented and tested, especially the new settings related to chunk management.


48-52: Confirm that the logging levels and formats are adequately configurable and meet the operational requirements.

Verification successful

The logging levels and formats are adequately configurable and are being read from the configuration file and applied properly in the application code. The relevant flags log_level and log_format are defined and used appropriately.

  • server/v2/streaming/plugin.md: The log level is read using appOpts.Get(flags.FlagLogLevel).
  • server/v2/logger.go: The log format and log level are read using v.GetString(FlagLogFormat) and v.GetString(FlagLogLevel) respectively.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for logging configuration usage in application code.

# Search for log level and format settings in the application.
rg --type toml 'log_level|log_format' server/v2/

Length of output: 152



Script:

#!/bin/bash
# Description: Check for logging configuration usage in application code.

# Search for log level and format settings usage in the application code.
rg 'log_level|log_format' server/v2/

Length of output: 368



Script:

#!/bin/bash
# Description: Extract relevant lines to verify usage of log_level and log_format.

# Extract lines from server/v2/flags.go and server/v2/cometbft/flags/flags.go
rg 'log_level|log_format' server/v2/flags.go server/v2/cometbft/flags/flags.go -A 5 -B 5

Length of output: 1258



Script:

#!/bin/bash
# Description: Verify if log_level and log_format flags are read from the configuration file and applied properly.

# Search for the usage of log_level and log_format flags in the application code.
rg 'FlagLogLevel|FlagLogFormat' server/v2/

Length of output: 506


182-191: Ensure that TLS configuration paths are validated during server startup to prevent runtime errors.


72-77: Validate that the abci connection types are correctly implemented in the server code.

Comment on lines +94 to +95
# Use '["*"]' to allow any origin
cors_allowed_origins = []
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a default CORS configuration for better out-of-the-box security.

Comment on lines +160 to +162
# Enabling this experimental parameter will cause the WebSocket connection to
# be closed instead if it cannot read fast enough, allowing for greater
# predictability in subscription behavior.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider implementing a more robust client management strategy to prevent silent event drops on slow WebSocket clients.

Comment on lines 28 to 32
func Commands(rootCmd *cobra.Command, newApp AppCreator[transaction.Tx], logger log.Logger, components ...ServerComponent[transaction.Tx]) (CLIConfig, error) {
if len(components) == 0 {
// TODO figure if we should define default components
// and if so it should be done here to avoid uncessary dependencies
return CLIConfig{}, errors.New("no components provided")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider providing default components when none are supplied.

The current implementation throws an error when no components are provided. Consider providing sensible defaults or a clear message guiding the user on how to supply components.

Comment on lines 94 to 111
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
home, err := cmd.Flags().GetString(flagHome)
if err != nil {
return err
}

err = configHandle(server, home, cmd)
if err != nil {
return err
}

if rootCmd.PersistentPreRun != nil {
rootCmd.PersistentPreRun(cmd, args)
return nil
}

return originalPersistentPreRunE(cmd, args)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper handling of PersistentPreRun.

The logic here overrides PersistentPreRunE but does not account for the possibility that PersistentPreRun might be set. Consider integrating or documenting how both should be handled to avoid confusion or unintended behavior.

+ if rootCmd.PersistentPreRun != nil {
+     rootCmd.PersistentPreRun(cmd, args)
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines 117 to 137
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
err = s.WriteConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
}

viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
viper.Set(flagHome, home)

log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}

return SetCmdServerContext(cmd, viper, log)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize configuration reading and context setting.

The current implementation of configHandle could be optimized by checking for the existence of the configuration directory early and simplifying error handling. Consider refactoring to reduce redundancy and improve clarity.

func configHandle(s *Server, home string, cmd *cobra.Command) error {
    configPath := filepath.Join(home, "config")
    if _, err := os.Stat(configPath); os.IsNotExist(err) {
        if err := s.WriteConfig(configPath); err != nil {
            return err
        }
    }

    viper, err := ReadConfig(configPath)
    if err != nil {
        return err
    }
    viper.Set(flagHome, home)

    log, err := NewLogger(viper, cmd.OutOrStdout())
    if err != nil {
        return err
    }

    return SetCmdServerContext(cmd, viper, log)
}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
err = s.WriteConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
}
viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
viper.Set(flagHome, home)
log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}
return SetCmdServerContext(cmd, viper, log)
}
func configHandle(s *Server, home string, cmd *cobra.Command) error {
configPath := filepath.Join(home, "config")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if err := s.WriteConfig(configPath); err != nil {
return err
}
}
viper, err := ReadConfig(configPath)
if err != nil {
return err
}
viper.Set(flagHome, home)
log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}
return SetCmdServerContext(cmd, viper, log)
}

server/v2/commands.go Outdated Show resolved Hide resolved
Comment on lines +270 to +318
#
# Possible types:
# - "flood" : concurrent linked list mempool with flooding gossip protocol
# (default)
# - "nop" : nop-mempool (short for no operation; the ABCI app is responsible
# for storing, disseminating and proposing txs). "create_empty_blocks=false" is
# not supported.
type = "flood"

# Recheck (default: true) defines whether CometBFT should recheck the
# validity for all remaining transaction in the mempool after a block.
# Since a block affects the application state, some transactions in the
# mempool may become invalid. If this does not apply to your application,
# you can disable rechecking.
recheck = true

# Broadcast (default: true) defines whether the mempool should relay
# transactions to other peers. Setting this to false will stop the mempool
# from relaying transactions to other peers until they are included in a
# block. In other words, if Broadcast is disabled, only the peer you send
# the tx to will see it until it is included in a block.
broadcast = true

# WalPath (default: "") configures the location of the Write Ahead Log
# (WAL) for the mempool. The WAL is disabled by default. To enable, set
# WalPath to where you want the WAL to be written (e.g.
# "data/mempool.wal").
wal_dir = ""

# Maximum number of transactions in the mempool
size = 5000

# Limit the total size of all txs in the mempool.
# This only accounts for raw transactions (e.g. given 1MB transactions and
# max_txs_bytes=5MB, mempool will only accept 5 transactions).
max_txs_bytes = 1073741824

# Size of the cache (used to filter transactions we saw earlier) in transactions
cache_size = 10000

# Do not remove invalid transactions from the cache (default: false)
# Set to true if it's not possible for any invalid transaction to become valid
# again in the future.
keep-invalid-txs-in-cache = false

# Maximum size of a single transaction.
# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}.
max_tx_bytes = 1048576

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The search results indicate that several mempool configuration options listed in config.toml are not defined or used in the current Go codebase. Specifically, options such as recheck, wal_dir, size, max_txs_bytes, cache_size, keep-invalid-txs-in-cache, and max_tx_bytes are not present.

  • server/v2/cometbft/mempool/config.go defines only the MaxTxs option.
  • The searches for other configuration options yielded no relevant results, except for a mention of broadcast-mode in flags.go, which appears unrelated to mempool configuration.

The current implementation does not support all the mempool configuration options specified in config.toml.

Analysis chain

Check that all mempool configuration options are supported by the current mempool implementation.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify mempool configuration options.

# Search for mempool configuration usage in the application.
rg --type go 'mempool' server/v2/

Length of output: 4478



Script:

#!/bin/bash
# Extract mempool configuration options from the config.go file

# Display the content of config.go to review the configuration options
cat server/v2/cometbft/mempool/config.go

Length of output: 485



Script:

#!/bin/bash
# Search for the missing mempool configuration options in the codebase

# Search for the 'recheck' option in the codebase
rg --type go 'recheck' server/v2/

# Search for the 'broadcast' option in the codebase
rg --type go 'broadcast' server/v2/

# Search for the 'wal_dir' option in the codebase
rg --type go 'wal_dir' server/v2/

# Search for the 'size' option in the codebase
rg --type go 'size' server/v2/

# Search for the 'max_txs_bytes' option in the codebase
rg --type go 'max_txs_bytes' server/v2/

# Search for the 'cache_size' option in the codebase
rg --type go 'cache_size' server/v2/

# Search for the 'keep-invalid-txs-in-cache' option in the codebase
rg --type go 'keep-invalid-txs-in-cache' server/v2/

# Search for the 'max_tx_bytes' option in the codebase
rg --type go 'max_tx_bytes' server/v2/

Length of output: 20617

server/v2/api/grpc/server.go Outdated Show resolved Hide resolved
Comment on lines 80 to 91
// Add empty server struct here for writing default config
err := serverv2.AddCommands(
rootCmd,
newApp,
log.NewNopLogger(),
cometbft.New(&temporaryTxDecoder{txConfig}),
grpc.NewGRPCServer(),
)
if err != nil {
panic(fmt.Sprintf("Add cmd, %v", err))
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The initRootCmd function adds various commands to the root command. The use of panic on error (line 89) is a bit harsh for error handling in a CLI application. Consider changing this to log the error and exit gracefully.

- panic(fmt.Sprintf("Add cmd, %v", err))
+ log.Fatalf("Failed to add command: %v", err)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Add empty server struct here for writing default config
err := serverv2.AddCommands(
rootCmd,
newApp,
log.NewNopLogger(),
cometbft.New(&temporaryTxDecoder{txConfig}),
grpc.NewGRPCServer(),
)
if err != nil {
panic(fmt.Sprintf("Add cmd, %v", err))
}
// Add empty server struct here for writing default config
err := serverv2.AddCommands(
rootCmd,
newApp,
log.NewNopLogger(),
cometbft.New(&temporaryTxDecoder{txConfig}),
grpc.NewGRPCServer(),
)
if err != nil {
log.Fatalf("Failed to add command: %v", err)
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Outside diff range and nitpick comments (1)
server/v2/testdata/config.toml (1)

94-95: The CORS configuration is disabled by default (cors_allowed_origins = []). Confirm if this is the intended behavior, as it might restrict client interactions in some deployment scenarios.

Consider providing examples or additional comments on enabling CORS for specific scenarios.

Also applies to: 98-98, 101-101

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d014b2 and a53bec5.

Files ignored due to path filters (2)
  • server/v2/cometbft/go.sum is excluded by !**/*.sum
  • server/v2/go.sum is excluded by !**/*.sum
Files selected for processing (16)
  • runtime/v2/app.go (1 hunks)
  • server/v2/api/grpc/server.go (3 hunks)
  • server/v2/cometbft/go.mod (3 hunks)
  • server/v2/cometbft/server.go (7 hunks)
  • server/v2/commands.go (2 hunks)
  • server/v2/go.mod (6 hunks)
  • server/v2/server.go (6 hunks)
  • server/v2/server_mock_test.go (2 hunks)
  • server/v2/server_test.go (3 hunks)
  • server/v2/testdata/config.toml (1 hunks)
  • server/v2/types.go (1 hunks)
  • server/v2/util.go (1 hunks)
  • simapp/v2/app_di.go (2 hunks)
  • simapp/v2/go.mod (2 hunks)
  • simapp/v2/simdv2/cmd/commands.go (6 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (3 hunks)
Files skipped from review due to trivial changes (1)
  • simapp/v2/simdv2/cmd/root_di.go
Additional context used
Path-based instructions (11)
server/v2/types.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server_mock_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/util.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

runtime/v2/app.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/grpc/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/app_di.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/cometbft/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

GitHub Check: gosec
server/v2/commands.go

[warning] 54-54: Errors unhandled.
Errors unhandled.


[warning] 46-46: Errors unhandled.
Errors unhandled.

server/v2/server.go

[failure] 173-173: Expect directory permissions to be 0750 or less
Expect directory permissions to be 0750 or less

Additional comments not posted (34)
server/v2/types.go (1)

9-14: The Application interface is well-defined and aligns with the objectives of providing a structured way to manage applications.

server/v2/util.go (2)

32-39: The GetViperFromCmd function correctly retrieves a Viper instance from the command context. It properly handles type assertion and returns a new Viper instance if the assertion fails, which is a good fallback mechanism.


51-58: GetLoggerFromCmd retrieves a logger from the command context. This function is implemented correctly with appropriate fallbacks.

server/v2/server_test.go (2)

119-133: The TestReadConfig function is well-structured and tests the configuration reading functionality effectively. Using require.NoError for assertions is appropriate and makes the tests cleaner.


50-58: The test TestServer sets up a server and tests various configurations. Ensure that error handling is robust, particularly in the configuration reading and server starting/stopping phases.

Verification successful

The TestServer function in server/v2/server_test.go includes error handling for various stages, such as reading the configuration, starting the server, and stopping the server. Errors are logged and cause the test to fail, ensuring that issues are caught during testing.

  • Error handling when getting the current directory:

    currentDir, err := os.Getwd()
    if err != nil {
        t.Log(err)
        t.Fail()
    }
  • Error handling when reading the configuration:

    v, err := serverv2.ReadConfig(configPath)
    if err != nil {
        v = viper.New()
    }
  • Error handling when creating the gRPC server:

    grpcServer, err := grpc.New(logger, v, &mockInterfaceRegistry{})
    if err != nil {
        t.Log(err)
        t.Fail()
    }
  • Error handling when writing the configuration:

    if err := server.WriteConfig(configPath); err != nil {
        t.Log(err)
        t.Fail()
    }
  • Error handling when reading the configuration again:

    v, err = serverv2.ReadConfig(configPath)
    if err != nil {
        t.Log(err)
        t.FailNow()
    }
  • Error handling when stopping the server:

    if err := server.Stop(ctx); err != nil {
        t.Logf("failed to stop servers: %s", err)
        t.Fail()
    }
  • Error handling when starting the server:

    if err := server.Start(ctx); err != nil {
        t.Log(err)
        t.Fail()
    }

The test function logs errors and fails the test appropriately, ensuring robust error handling. Thus, the review comment's concern about error handling is addressed correctly in the test code.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify robust error handling in server start and stop.

# Test: Check logs for error messages during server operations.
cat logs/server_test.log | grep "error"

Length of output: 92



Script:

#!/bin/bash
# Description: Check for error handling in the TestServer function.

# Search for the TestServer function definition and its error handling mechanisms.
ast-grep --lang go --pattern $'func TestServer($_) {
  $$$
}' server/v2/server_test.go

Length of output: 3937

server/v2/commands.go (5)

14-16: The imports for cosmossdk.io/core/transaction and cosmossdk.io/log seem appropriate for the operations in this file. Also, the addition of github.com/spf13/viper is necessary for the configuration management enhancements described in the PR.


21-24: The App struct is well-defined, encapsulating the application logic and storage. This struct serves as a foundational element for operations within the server, adhering to clean code principles by keeping related data together.


26-26: The AppCreator type is a functional approach to creating app instances. It abstracts the instantiation logic, allowing for flexible and testable code.
[APROVED]


28-32: The error handling in the Commands function is appropriate as it prevents proceeding without any server components. This is a good practice as it enforces the requirement of components for the server's operation.


86-112: The AddCommands function integrates the commands setup with the server configuration and handles errors appropriately. However, the handling of PersistentPreRunE should also consider the possibility of PersistentPreRun being set, as suggested in previous comments.

Verification successful

The AddCommands function appropriately handles both PersistentPreRunE and PersistentPreRun. The logic ensures that if PersistentPreRun is set, it is called before the original PersistentPreRunE. This confirms that the review comment is accurate.

  • server/v2/commands.go:
    • Lines 86-112: Correct handling of PersistentPreRunE and PersistentPreRun.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the handling of PersistentPreRunE and PersistentPreRun
rg --type go 'PersistentPreRun'

Length of output: 779

runtime/v2/app.go (1)

138-140: The GetAppManager method is a straightforward accessor for AppManager. It's a clean and simple addition that follows good coding practices by providing encapsulated access to internal components.

server/v2/go.mod (2)

9-9: The replacement directive for cosmossdk.io/log to ../../log ensures that local changes in the log module are used during development. This is a good practice for testing local modifications before they are merged into the main branch.


20-21: The addition of github.com/cometbft/cometbft as a required module aligns with the PR's objectives to integrate CometBFT functionalities. This change is necessary for the new features introduced in the server module.

server/v2/server.go (1)

18-24: The ServerComponent interface definition is robust, encapsulating the necessary operations for server components. The inclusion of Init method in the interface is critical for initializing components with specific configurations and logging capabilities.

server/v2/api/grpc/server.go (3)

Line range hint 91-91: The implementation of the gRPC server starting mechanism is robust and correctly handles errors.


Line range hint 104-104: The graceful stop implementation for the gRPC server is correctly done.


Line range hint 44-58: Ensure that the RegisterGRPCServer method is called to register necessary gRPC services.

simapp/v2/simdv2/cmd/commands.go (3)

53-59: The newApp function correctly initializes a new application instance using the SimApp constructor.


80-91: The initialization of root commands is done correctly, and error handling is appropriate for a CLI context.


Line range hint 162-162: The implementation of the appExport function is robust, handling various edge cases and errors appropriately.

simapp/v2/app_di.go (1)

238-238: The InterfaceRegistry method is implemented correctly, providing access to the application's interface registry.

server/v2/cometbft/server.go (3)

Line range hint 74-108: The Init method for CometBFTServer is implemented correctly, handling configuration and initialization logic appropriately.


113-113: The Start method for CometBFTServer is robust, correctly handling different operational modes and errors.


243-247: The WriteDefaultConfigAt method correctly handles the creation of default configuration files for the CometBFT server.

server/v2/cometbft/go.mod (2)

10-10: Added a replace directive for cosmossdk.io/log.

This ensures that the local log module is used instead of pulling from an external source, which can be beneficial for local development and testing. Make sure that the local path is correctly set up to point to the existing log module.


42-42: Added github.com/spf13/viper v1.19.0 to manage application configuration.

This addition is in line with the PR's objective to enhance config management capabilities. viper is widely used for handling configurations due to its versatility and support for multiple config formats.

simapp/v2/go.mod (3)

13-13: Updated dependency on cosmossdk.io/server/v2 and cosmossdk.io/server/v2/cometbft.

This update is necessary to align with the new functionalities introduced in the server/v2 module as per the PR objectives. It ensures that simapp/v2 uses the latest changes, including the new cometbft module.


45-45: Added golang.org/x/sync v0.7.0 as an indirect dependency.

This inclusion is likely for improved synchronization utilities in Go, which might be indirectly required by other dependencies. It's a good practice to explicitly list out indirect dependencies for clearer dependency management.


49-52: Added new requirements for cosmossdk.io/client/v2 and cosmossdk.io/tools/confix.

These additions are part of enhancing the simapp/v2 module's capability to interact with the server components and manage configurations effectively. Ensure that these modules are properly versioned and maintained to avoid future compatibility issues.

server/v2/testdata/config.toml (5)

114-114: The connection limits (grpc_max_open_connections and max_open_connections) are both set to 900. Ensure that these settings are tuned based on the expected load and system capabilities.

Also applies to: 126-126

Verification successful

The connection limits (grpc_max_open_connections and max_open_connections) are both set to 900, which is significantly lower than the system's file descriptor limit of 25000. This indicates that the settings are appropriately tuned for the system's capabilities.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check system limits to ensure the connection settings are appropriate.

# Test: Check the system's file descriptor limits.
ulimit -Sn

Length of output: 18


11-11: Ensure that the version 0.38.7 is the correct and latest version supported by CometBFT.

Verification successful

The version 0.38.7 specified in the config.toml file is indeed the latest version supported by CometBFT, as confirmed by the latest release tag from the official CometBFT GitHub repository.

  • server/v2/testdata/config.toml: version = "0.38.7"
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the latest version of CometBFT in the repository.

# Test: Search for the latest version in the go.mod file of CometBFT.
rg --type toml "version =" server/v2/cometbft/go.mod

Length of output: 54



Script:

#!/bin/bash
# Description: Verify the latest version of CometBFT by checking the official repository and other relevant files.

# Test 1: Search for the latest version in the repository files.
rg --type toml "version ="

# Test 2: Check the official CometBFT GitHub repository for the latest release tag.
gh release list -R cometbft/cometbft --limit 1

Length of output: 9593


19-19: Confirm that the default configurations provided align with the expected defaults for a production environment, and consider adding comments to guide users on when they might want to change these settings.

Also applies to: 43-43, 56-56, 60-60, 63-63, 70-70, 73-73


277-277: The mempool configuration defaults (type = "flood", recheck = true, broadcast = true) are standard, but it's important to ensure they are the best fit for the network's transaction patterns and load.

Also applies to: 284-284, 291-291


169-169: The timeout setting for /broadcast_tx_commit is set to 10 seconds. Verify that this value meets the performance expectations and adjust if necessary to avoid potential bottlenecks.

Comment on lines 57 to 59
func (s *mockServer) Init(appI serverv2.App[transaction.Tx], v *viper.Viper, logger log.Logger) (serverv2.ServerComponent[transaction.Tx], error) {
return nil, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Init method in mockServer is a stub with no implementation. Ensure this method is properly implemented or documented if it is intended to remain a stub.

Comment on lines 17 to 30
func SetCmdServerContext(cmd *cobra.Command, viper *viper.Viper, logger log.Logger) error {
var cmdCtx context.Context

if cmd.Context() == nil {
cmdCtx = context.Background()
} else {
cmdCtx = cmd.Context()
}

cmd.SetContext(context.WithValue(cmdCtx, corectx.LoggerContextKey{}, logger))
cmd.SetContext(context.WithValue(cmdCtx, corectx.ViperContextKey{}, viper))

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The SetCmdServerContext function properly sets up the command context with logger and viper instances. However, consider adding error handling for context-related operations to enhance robustness.

Comment on lines 41 to 49
func GetConfigFromViper(v *viper.Viper) *cmtcfg.Config {
conf := cmtcfg.DefaultConfig()
err := v.Unmarshal(conf)
rootDir := v.GetString("home")
if err != nil {
return cmtcfg.DefaultConfig().SetRoot(rootDir)
}
return conf.SetRoot(rootDir)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The GetConfigFromViper function attempts to unmarshal the configuration into a Config object. However, consider adding more robust error handling and logging to provide better insights into why unmarshaling might fail.

[rpc]

# TCP or UNIX socket address for the RPC server to listen on
laddr = "tcp://127.0.0.1:26657"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review the network configuration settings to ensure they are secure and appropriate for the intended deployment environment. Consider restricting the grpc_laddr to a non-empty default to prevent unintentional exposure.

- grpc_laddr = ""
+ grpc_laddr = "tcp://127.0.0.1:9090" # Suggested default for local connections only

Also applies to: 103-105

[p2p]

# Address to listen for incoming connections
laddr = "tcp://0.0.0.0:26656"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The laddr for P2P connections is set to listen on all interfaces (0.0.0.0). This could pose a security risk if the node is directly accessible from the internet.

- laddr = "tcp://0.0.0.0:26656"
+ laddr = "tcp://127.0.0.1:26656" # Suggested change for increased security in default configurations
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
laddr = "tcp://0.0.0.0:26656"
laddr = "tcp://127.0.0.1:26656" # Suggested change for increased security in default configurations

Comment on lines 54 to 55
server.Init(app, v, l)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The call to server.Init(app, v, l) lacks error handling, which could lead to issues if the initialization fails. Proper error management is crucial in this context.

- server.Init(app, v, l)
+ if err := server.Init(app, v, l); err != nil {
+     return err
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
server.Init(app, v, l)
if err := server.Init(app, v, l); err != nil {
return err
}
Tools
GitHub Check: gosec

[warning] 54-54: Errors unhandled.
Errors unhandled.

server/v2/commands.go Outdated Show resolved Hide resolved
Comment on lines 117 to 137
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
err = s.WriteConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
}

viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
viper.Set(flagHome, home)

log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}

return SetCmdServerContext(cmd, viper, log)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The configHandle function performs essential configuration management tasks. However, the error handling within this function could be improved by adding detailed error messages, especially when configuration files are missing or incorrect.

- return err
+ return fmt.Errorf("error processing configuration at %s: %w", filepath.Join(home, "config"), err)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
err = s.WriteConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
}
viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
viper.Set(flagHome, home)
log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}
return SetCmdServerContext(cmd, viper, log)
}
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
err = s.WriteConfig(filepath.Join(home, "config"))
if err != nil {
return fmt.Errorf("error processing configuration at %s: %w", filepath.Join(home, "config"), err)
}
}
viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return fmt.Errorf("error processing configuration at %s: %w", filepath.Join(home, "config"), err)
}
viper.Set(flagHome, home)
log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return fmt.Errorf("error processing configuration at %s: %w", filepath.Join(home, "config"), err)
}
return SetCmdServerContext(cmd, viper, log)
}

Comment on lines 148 to 161
func (s *Server) Init(appI App[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, err
}
components = append(components, module)
}
s.components = components

return s, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Init method in the Server struct properly initializes each component, but it should handle errors in a way that does not proceed with initialization if one component fails. This ensures that the server does not run in an unstable state.

- return nil, err
+ return nil, fmt.Errorf("failed to initialize component %s: %w", mod.Name(), err)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *Server) Init(appI App[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, err
}
components = append(components, module)
}
s.components = components
return s, nil
}
func (s *Server) Init(appI App[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, fmt.Errorf("failed to initialize component %s: %w", mod.Name(), err)
}
components = append(components, module)
}
s.components = components
return s, nil
}

@github-actions github-actions bot added C:CLI C:x/genutil genutil module issues labels Jun 19, 2024
Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK. We'll need to iterate on this (genutil + export), but this is gtm!

server/v2/go.mod Outdated Show resolved Hide resolved
type AppCreator[T transaction.Tx] func(log.Logger, *viper.Viper) AppI[T]

type AppI[T transaction.Tx] interface {
GetAppManager() *appmanager.AppManager[T]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we create and expected interface here for appmanager? best not to tie it to our implementation

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's do it in a follow up, other deps is removed now though

server/v2/util.go Outdated Show resolved Hide resolved
Copy link
Member

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left a few commnents we should address but we can merge and handle on main

@julienrbrt julienrbrt changed the title feat(server/v2) add config & start helper feat(server/v2): add config & start helper Jun 19, 2024
@julienrbrt julienrbrt added this pull request to the merge queue Jun 19, 2024
Merged via the queue into main with commit 8ab643d Jun 19, 2024
68 of 70 checks passed
@julienrbrt julienrbrt deleted the hieu/v2_config_start branch June 19, 2024 17:24
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Outside diff range and nitpick comments (2)
x/genutil/client/cli/commands.go (1)

15-16: Ensure to address the TODO comments regarding server v2 dependencies.

Consider replacing these TODO comments with actual implementation or more detailed comments to guide future developers.

server/v2/server.go (1)

7-7: Consider using a more descriptive variable name than v for the viper instance to enhance code readability.

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a53bec5 and f4c1db7.

Files ignored due to path filters (1)
  • server/v2/go.sum is excluded by !**/*.sum
Files selected for processing (21)
  • runtime/v2/app.go (1 hunks)
  • scripts/simapp-v2-init.sh (1 hunks)
  • server/v2/api/grpc/server.go (2 hunks)
  • server/v2/cometbft/config.go (1 hunks)
  • server/v2/cometbft/server.go (7 hunks)
  • server/v2/commands.go (2 hunks)
  • server/v2/flags.go (1 hunks)
  • server/v2/go.mod (4 hunks)
  • server/v2/server.go (6 hunks)
  • server/v2/server_mock_test.go (2 hunks)
  • server/v2/server_test.go (4 hunks)
  • server/v2/testdata/app.toml (1 hunks)
  • server/v2/types.go (1 hunks)
  • server/v2/util.go (1 hunks)
  • simapp/v2/app_di.go (5 hunks)
  • simapp/v2/go.mod (3 hunks)
  • simapp/v2/simdv2/cmd/commands.go (6 hunks)
  • simapp/v2/simdv2/cmd/config.go (2 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (5 hunks)
  • simapp/v2/simdv2/main.go (1 hunks)
  • x/genutil/client/cli/commands.go (1 hunks)
Files skipped from review due to trivial changes (5)
  • server/v2/flags.go
  • server/v2/server_test.go
  • server/v2/testdata/app.toml
  • simapp/v2/simdv2/cmd/config.go
  • simapp/v2/simdv2/main.go
Files skipped from review as they are similar to previous changes (10)
  • runtime/v2/app.go
  • server/v2/api/grpc/server.go
  • server/v2/cometbft/server.go
  • server/v2/go.mod
  • server/v2/server_mock_test.go
  • server/v2/types.go
  • server/v2/util.go
  • simapp/v2/go.mod
  • simapp/v2/simdv2/cmd/commands.go
  • simapp/v2/simdv2/cmd/root_di.go
Additional context used
Path-based instructions (5)
x/genutil/client/cli/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/cometbft/config.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/app_di.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Shellcheck
scripts/simapp-v2-init.sh

[warning] 16-16: Quote this to prevent word splitting. (SC2046)

GitHub Check: gosec
server/v2/server.go

[failure] 173-173: Expect directory permissions to be 0750 or less
Expect directory permissions to be 0750 or less

Additional comments not posted (3)
server/v2/cometbft/config.go (1)

12-21: Refactor the error handling logic for clarity and efficiency.
[REFACTOR_SUGGESTion]
The current implementation repeats the default configuration creation. Consider simplifying this by using a single return statement.

func GetConfigFromViper(v *viper.Viper) *cmtcfg.Config {
	conf := cmtcfg.DefaultConfig()
	rootDir := v.GetString(serverv2.FlagHome)
	if err := v.Unmarshal(conf); err != nil {
		conf.SetRoot(rootDir)
	}
	return conf.SetRoot(rootDir)
}
server/v2/server.go (1)

47-58: Ensure proper error handling in ReadConfig to avoid silent failures or crashes due to configuration issues.

Verification successful

The ReadConfig function in server/v2/server.go appears to handle errors properly by returning formatted error messages when ReadInConfig or MergeInConfig fail. Here are the relevant lines:

if err := v.ReadInConfig(); err != nil {
    return nil, fmt.Errorf("failed to read config: %s: %w", configPath, err)
}

if err := v.MergeInConfig(); err != nil {
    return nil, fmt.Errorf("failed to merge configuration: %w", err)
}

The function also returns a nil value for the *viper.Viper type in case of an error, which is appropriate for error handling.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify proper error handling in `ReadConfig`
rg --type go 'ReadConfig' server/v2/server.go

Length of output: 104



Script:

#!/bin/bash
# Extract the full implementation of ReadConfig function
ast-grep --lang go --pattern 'func ReadConfig($_) $_' server/v2/server.go

Length of output: 965

simapp/v2/app_di.go (1)

129-129: Ensure that servertypes.AppOptions(viper) is correctly retrieving and applying configuration options. Verify that all necessary configurations are included.

Comment on lines +173 to +175
if err := os.MkdirAll(configPath, os.ModePerm); err != nil {
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjust directory permissions for security best practices.

- if err := os.MkdirAll(configPath, os.ModePerm); err != nil {
+ if err := os.MkdirAll(configPath, 0750); err != nil {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := os.MkdirAll(configPath, os.ModePerm); err != nil {
return err
}
if err := os.MkdirAll(configPath, 0750); err != nil {
return err
}
Tools
GitHub Check: gosec

[failure] 173-173: Expect directory permissions to be 0750 or less
Expect directory permissions to be 0750 or less

Comment on lines +148 to +161
func (s *Server) Init(appI AppI[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, err
}
components = append(components, module)
}
s.components = components

return s, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Init method should handle errors more gracefully to prevent the server from running in an unstable state.

- return nil, err
+ return nil, fmt.Errorf("failed to initialize component %s: %w", mod.Name(), err)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *Server) Init(appI AppI[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, err
}
components = append(components, module)
}
s.components = components
return s, nil
}
func (s *Server) Init(appI AppI[transaction.Tx], v *viper.Viper, logger log.Logger) (ServerComponent[transaction.Tx], error) {
var components []ServerComponent[transaction.Tx]
for _, mod := range s.components {
mod := mod
module, err := mod.Init(appI, v, logger)
if err != nil {
return nil, fmt.Errorf("failed to initialize component %s: %w", mod.Name(), err)
}
components = append(components, module)
}
s.components = components
return s, nil
}

) *SimApp {
homeDir := appOpts.Get("home").(string) // TODO
homeDir := viper.Get(flags.FlagHome).(string) // TODO
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use of viper.Get(flags.FlagHome).(string) can lead to a runtime panic if the type assertion fails. Consider adding a type check.

- homeDir := viper.Get(flags.FlagHome).(string) // TODO
+ homeDir, ok := viper.Get(flags.FlagHome).(string)
+ if !ok {
+     return nil, fmt.Errorf("invalid type for home directory")
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
homeDir := viper.Get(flags.FlagHome).(string) // TODO
homeDir, ok := viper.Get(flags.FlagHome).(string)
if !ok {
return nil, fmt.Errorf("invalid type for home directory")
}

@@ -13,13 +13,12 @@ CONFIG="${CONFIG:-$HOME/.simappv2/config}"
cd "$SIMAPP_DIR"
go build -o "$ROOT/build/simdv2" simdv2/main.go

if [ -d "$($SIMD config home)" ]; then rm -r $($SIMD config home); fi
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quote the command substitution to prevent word splitting.

- if [ -d "$($SIMD config home)" ]; then rm -r $($SIMD config home); fi
+ if [ -d "$($SIMD config home)" ]; then rm -r "$($SIMD config home)"; fi
Tools
Shellcheck

[warning] 16-16: Quote this to prevent word splitting. (SC2046)

Comment on lines +18 to +20
func Commands(rootCmd *cobra.Command, newApp AppCreator[transaction.Tx], logger log.Logger, components ...ServerComponent[transaction.Tx]) (CLIConfig, error) {
if len(components) == 0 {
return CLIConfig{}, errors.New("no components provided")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle the case where no components are provided more gracefully.

Consider providing a default component or a more informative error message to guide the user.

if len(components) == 0 {
	return CLIConfig{}, fmt.Errorf("no server components provided. Please ensure at least one component is configured.")
}


app := newApp(l, v)

if _, err := server.Init(app, v, l); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure error handling is implemented for server initialization.

The error handling for server initialization is crucial and should be clearly checked.

if _, err := server.Init(app, v, l); err != nil {
	return fmt.Errorf("server initialization failed: %w", err)
}

Comment on lines +110 to +133
// configHandle writes the default config to the home directory if it does not exist and sets the server context
func configHandle(s *Server, home string, cmd *cobra.Command) error {
if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) {
if err = s.WriteConfig(filepath.Join(home, "config")); err != nil {
return err
}
}

viper, err := ReadConfig(filepath.Join(home, "config"))
if err != nil {
return err
}
viper.Set(FlagHome, home)
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return err
}

log, err := NewLogger(viper, cmd.OutOrStdout())
if err != nil {
return err
}

return SetCmdServerContext(cmd, viper, log)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the configuration handling function to improve clarity and error management.

This function can be optimized by consolidating error checks and improving the error messages.

func configHandle(s *Server, home string, cmd *cobra.Command) error {
	configPath := filepath.Join(home, "config")
	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		if err = s.WriteConfig(configPath); err != nil {
			return fmt.Errorf("failed to write config to %s: %w", configPath, err)
		}
	}

	viper, err := ReadConfig(configPath)
	if err != nil {
		return fmt.Errorf("failed to read config from %s: %w", configPath, err)
	}
	viper.Set(FlagHome, home)

	if err := viper.BindPFlags(cmd.Flags()); err != nil {
		return fmt.Errorf("failed to bind command flags: %w", err)
	}

	log, err := NewLogger(viper, cmd.OutOrStdout())
	if err != nil {
		return fmt.Errorf("failed to initialize logger: %w", err)
	}

	return SetCmdServerContext(cmd, viper, log)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

server/v2 start commands and helpers
5 participants