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

chore: use fetcher controller #87

Merged
merged 7 commits into from
Jan 7, 2025
Merged

Conversation

freak12techno
Copy link
Collaborator

@freak12techno freak12techno commented Jan 7, 2025

Summary by CodeRabbit

I'll provide concise release notes focusing on the key user-visible changes:

  • New Features

    • Introduced a new Controller component to manage data fetching across multiple sources.
    • Enhanced fetcher interfaces with dependency tracking and more flexible data retrieval.
  • Improvements

    • Streamlined data fetching and state management processes.
    • Improved type safety in data retrieval mechanisms.
    • Simplified state handling across generators and fetchers.
  • Technical Enhancements

    • Refactored state management to use a more flexible map-based approach.
    • Updated method signatures to improve code clarity and type handling.
    • Introduced generic functions for more robust data type conversions.

These changes primarily focus on internal architectural improvements to enhance the application's data fetching and processing capabilities.

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Warning

Rate limit exceeded

@freak12techno has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 35 minutes and 47 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e9653c4 and 4ae50ab.

📒 Files selected for processing (26)
  • pkg/controller/controller.go (1 hunks)
  • pkg/controller/controller_test.go (1 hunks)
  • pkg/generators/active_set_tokens.go (1 hunks)
  • pkg/generators/active_set_tokens_test.go (1 hunks)
  • pkg/generators/balance.go (1 hunks)
  • pkg/generators/commission.go (1 hunks)
  • pkg/generators/consumer_info.go (1 hunks)
  • pkg/generators/consumer_needs_to_sign.go (1 hunks)
  • pkg/generators/delegations.go (1 hunks)
  • pkg/generators/inflation.go (1 hunks)
  • pkg/generators/node_info.go (1 hunks)
  • pkg/generators/price.go (1 hunks)
  • pkg/generators/rewards.go (1 hunks)
  • pkg/generators/self_delegation.go (1 hunks)
  • pkg/generators/signing_info.go (1 hunks)
  • pkg/generators/single_validator_info.go (1 hunks)
  • pkg/generators/slashing_params.go (1 hunks)
  • pkg/generators/staking_params.go (1 hunks)
  • pkg/generators/supply.go (1 hunks)
  • pkg/generators/unbonds.go (1 hunks)
  • pkg/generators/validator_active.go (3 hunks)
  • pkg/generators/validator_commission_rate.go (2 hunks)
  • pkg/generators/validator_rank.go (1 hunks)
  • pkg/generators/validators_info.go (1 hunks)
  • pkg/state/state.go (1 hunks)
  • pkg/state/state_test.go (1 hunks)

Walkthrough

The pull request introduces a comprehensive refactoring of the application's architecture, focusing on enhancing the data fetching and state management processes. A new Controller component is introduced to centralize and streamline the fetching of data across various fetchers. The changes modify the Fetcher interface, add dependency management capabilities, and update the state management approach from a struct-based to a map-based implementation. The modifications aim to improve type safety, simplify data retrieval, and provide more flexible fetching mechanisms.

Changes

File Change Summary
pkg/app.go Added Controller field to App struct, updated Handler method to use new controller for fetching.
pkg/controller/controller.go New package with Controller implementation for managing fetchers concurrently.
pkg/fetchers/fetcher.go Updated Fetcher interface with new Dependencies() method and variadic Fetch() parameter.
Multiple fetcher files Added Dependencies() method and modified Fetch() method signature across all fetchers.
pkg/state/state.go Transformed State from struct to map, added generic data retrieval methods.
Multiple generator files Updated Generate() method signatures to accept State as value instead of pointer.
pkg/constants/constants.go Added new constants FetcherNameStub1 and FetcherNameStub2.
pkg/fetchers/stub.go Introduced StubFetcher1 and StubFetcher2 types with required methods.

Sequence Diagram

sequenceDiagram
    participant App
    participant Controller
    participant Fetchers
    participant State

    App->>Controller: Fetch()
    Controller->>Fetchers: Process fetchers with dependencies
    Fetchers-->>Controller: Return data and query info
    Controller-->>State: Update state with fetched data
    Controller-->>App: Return state and query info
Loading

Poem

🐰 A Rabbit's Refactoring Tale 🚀

In code's vast landscape, controllers rise,
Fetching data with concurrent ties
State transforms, a map so bright
Dependencies dance in pure delight
Simplicity reigns, complexity fades away! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jan 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (aa542a9) to head (4ae50ab).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##              main       #87    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           65        68     +3     
  Lines         3351      3457   +106     
==========================================
+ Hits          3351      3457   +106     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 6

🔭 Outside diff range comments (1)
pkg/fetchers/supply.go (1)

Line range hint 33-35: Fix incorrect logger component name.

The logger component name is set to "balance_fetcher" but should be "supply_fetcher".

-		Logger: logger.With().Str("component", "balance_fetcher").Logger(),
+		Logger: logger.With().Str("component", "supply_fetcher").Logger(),
🧹 Nitpick comments (35)
pkg/fetchers/has_to_validate.go (2)

52-52: Consider enhancing type safety and documentation for the variadic parameter.

While the variadic parameter allows for flexibility, using interface{} reduces type safety. Consider:

  1. Adding documentation to specify expected parameter types and usage
  2. Adding validation for passed arguments
  3. Using a more specific type or interface if possible

Example documentation:

// Fetch retrieves validator consumer data.
// Parameters:
//   - ctx: Context for the operation
//   - data: Optional parameters (currently unused)
// Returns:
//   - ValidatorConsumersData: The fetched data
//   - []*types.QueryInfo: Query information for telemetry

46-52: Solid implementation with good concurrency handling.

The changes align well with the architectural improvements while maintaining thread safety and proper error handling. The addition of the Dependencies method and modified Fetch signature provides a foundation for better fetcher orchestration.

Consider documenting the following aspects in the package documentation:

  1. The role of this fetcher in the new controller-based architecture
  2. The interaction pattern with other fetchers
  3. The threading model and synchronization guarantees
pkg/state/state.go (1)

52-54: Simplify nil pointer check without reflection

Using reflect to check for a nil pointer can impact performance. There is a simpler way to perform this check without reflection.

Use a direct comparison to nil:

-if reflect.ValueOf(data).Kind() == reflect.Ptr && reflect.ValueOf(data).IsNil() {
+if data == nil {
     return zero, false
 }

This approach is more efficient and straightforward.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 53-54: pkg/state/state.go#L53-L54
Added lines #L53 - L54 were not covered by tests

pkg/controller/controller.go (2)

88-91: Add test coverage for fetcher processing status check

The condition where a fetcher is already being processed or has been processed is not currently covered by unit tests. Adding tests for this scenario will help ensure that the controller correctly skips fetchers that are already processed, preventing potential issues during execution.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 88-91: pkg/controller/controller.go#L88-L91
Added lines #L88 - L91 were not covered by tests


95-98: Add test coverage for dependency resolution logic

The branch where a fetcher's dependencies have not yet been processed lacks test coverage. Including unit tests for this condition will verify that fetchers are appropriately deferred until their dependencies are satisfied, enhancing the reliability of the dependency management.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 95-98: pkg/controller/controller.go#L95-L98
Added lines #L95 - L98 were not covered by tests

pkg/generators/uptime.go (1)

19-19: Consider removing unused state parameter.

The state parameter is not used in this implementation. Consider either:

  1. Removing the parameter if it's not needed for the interface contract
  2. Adding a comment explaining why it's required by the interface but unused here
pkg/fetchers/fetcher.go (2)

10-13: Consider type safety improvements for Fetch method.

The variadic interface{} parameter might make it difficult to ensure type safety at compile time. Consider:

  1. Using generics to type-constrain the data parameters
  2. Adding documentation about expected types for the variadic parameters

11-11: Document the purpose of Dependencies method.

The new Dependencies method is a significant addition. Please add documentation explaining:

  1. Its purpose in preventing circular dependencies
  2. How it should be used by implementations
  3. Whether empty dependencies are valid
pkg/generators/inflation.go (1)

18-19: LGTM! Consider adding documentation for the new StateGet usage

The changes improve type safety by using the generic StateGet function and simplify the code by removing explicit type assertions. The switch to value-based state parameter is consistent with the architectural changes.

Consider adding a comment explaining the generic StateGet usage pattern for future maintainers.

pkg/generators/slashing_params.go (1)

18-19: LGTM! Consider documenting the new pattern

The changes consistently implement the new architecture using generic StateGet and value-based state parameter.

Since this pattern is repeated across multiple generators, consider:

  1. Adding documentation in a central location (e.g., README.md or package docs) explaining the new state management approach
  2. Creating an example generator implementation that showcases the best practices
pkg/generators/consumer_needs_to_sign.go (1)

21-28: LGTM! Consider consolidating state access

The implementation correctly applies type-safe state access. Consider creating a helper function to reduce duplication when accessing multiple state values, especially if this pattern appears in other generators.

Example helper:

func getMultipleState[T1, T2 any](
    state statePkg.State,
    key1, key2 string,
) (T1, T2, bool) {
    v1, ok := statePkg.StateGet[T1](state, key1)
    if !ok {
        return *new(T1), *new(T2), false
    }
    v2, ok := statePkg.StateGet[T2](state, key2)
    if !ok {
        return *new(T1), *new(T2), false
    }
    return v1, v2, true
}
pkg/fetchers/validators.go (1)

40-42: Consider documenting the purpose of Dependencies()

While the empty return is correct as this fetcher has no dependencies, adding a comment would help explain the method's role in the new Controller architecture.

+// Dependencies returns a list of fetchers that this fetcher depends on.
+// ValidatorsFetcher has no dependencies on other fetchers.
 func (q *ValidatorsFetcher) Dependencies() []constants.FetcherName {
 	return []constants.FetcherName{}
 }
pkg/fetchers/inflation.go (1)

42-44: Consider adding documentation for consistency

Similar to the validators fetcher, consider documenting the Dependencies method's purpose.

+// Dependencies returns a list of fetchers that this fetcher depends on.
+// InflationFetcher has no dependencies on other fetchers.
 func (q *InflationFetcher) Dependencies() []constants.FetcherName {
 	return []constants.FetcherName{}
 }
pkg/controller/controller_test.go (1)

24-24: Consider parameterizing hardcoded URLs and addresses.

The test uses hardcoded URLs and addresses which could make it brittle. Consider extracting these as test constants or configuration variables for better maintainability.

+const (
+    testAPIEndpoint = "https://api.cosmos.quokkastake.io"
+    testValidatorAddr = "cosmosvaloper1xqz9pemz5e5zycaa89kys5aw6m8rhgsvw4328e"
+    testDelegatorAddr = "cosmos1xqz9pemz5e5zycaa89kys5aw6m8rhgsvtp9lt2"
+)

Also applies to: 30-30

pkg/fetchers/staking_params.go (1)

40-42: Document the purpose of new interface methods.

The new Dependencies() method and variadic data parameter in Fetch() would benefit from documentation explaining:

  • The purpose of the empty dependency list
  • Expected types and usage of the variadic data parameter
  • How these changes integrate with the controller architecture

Also applies to: 45-46

pkg/fetchers/supply.go (1)

46-48: Document the purpose of Dependencies method.

Consider adding documentation to explain the role of the empty dependency list in the controller architecture.

pkg/fetchers/node_info.go (2)

46-48: Document the purpose of Dependencies method.

Consider adding documentation to explain the role of the empty dependency list in the controller architecture.


51-53: Enhance error handling and add context timeout.

Consider the following improvements:

  1. Add more context to error messages (e.g., include request details)
  2. Add a timeout to the context to prevent hanging in case of slow responses

Example implementation:

 func (q *NodeInfoFetcher) Fetch(
 	ctx context.Context,
 	data ...interface{},
 ) (interface{}, []*types.QueryInfo) {
+	// Add timeout to prevent hanging
+	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+	defer cancel()
 	...
 }

 func (q *NodeInfoFetcher) processChain(
 	ctx context.Context,
 	chainName string,
 	rpc *tendermint.RPC,
 ) {
 	defer q.wg.Done()
 	nodeInfo, query, err := rpc.GetNodeInfo(ctx)
 
 	q.mutex.Lock()
 	defer q.mutex.Unlock()
 
 	if query != nil {
 		q.queryInfos = append(q.queryInfos, query)
 	}
 
 	if err != nil {
 		q.Logger.Error().
 			Err(err).
 			Str("chain", chainName).
+			Str("endpoint", rpc.Endpoint).
+			Str("request", "GetNodeInfo").
 			Msg("Error querying node info")
 		return
 	}
 	...
 }

Also applies to: 89-103

pkg/fetchers/commission.go (1)

40-42: Consider documenting the purpose of the Dependencies method.

While the implementation is correct, adding documentation would help explain the method's role in the new controller-based architecture.

+// Dependencies returns a list of fetchers that this fetcher depends on.
+// Currently, CommissionFetcher has no dependencies.
 func (q *CommissionFetcher) Dependencies() []constants.FetcherName {
pkg/fetchers/unbonds.go (2)

40-42: Consider documenting the Dependencies method.

Similar to other fetchers, adding documentation would improve code clarity.

+// Dependencies returns a list of fetchers that this fetcher depends on.
+// Currently, UnbondsFetcher has no dependencies.
 func (q *UnbondsFetcher) Dependencies() []constants.FetcherName {

Line range hint 48-57: Consider initializing the map outside the loop for consistency.

The map initialization pattern differs from other fetchers. Consider moving it before the loop to match the pattern used in commission.go:

 	allUnbonds := map[string]map[string]uint64{}
+	for _, chain := range q.Chains {
+		allUnbonds[chain.Name] = map[string]uint64{}
+	}
 
 	var wg sync.WaitGroup
 	var mutex sync.Mutex
 
 	for _, chain := range q.Chains {
-		mutex.Lock()
-		allUnbonds[chain.Name] = map[string]uint64{}
-		mutex.Unlock()
pkg/fetchers/slashing_params.go (2)

46-48: Consider documenting the Dependencies method.

Add documentation to maintain consistency with other fetchers.

+// Dependencies returns a list of fetchers that this fetcher depends on.
+// Currently, SlashingParamsFetcher has no dependencies.
 func (q *SlashingParamsFetcher) Dependencies() []constants.FetcherName {

Line range hint 16-21: Consider initializing sync primitives in constructor.

The sync primitives are declared as struct fields but not initialized in the constructor. This could lead to issues if the fetcher is reused.

 func NewSlashingParamsFetcher(
 	logger *zerolog.Logger,
 	chains []*config.Chain,
 	rpcs map[string]*tendermint.RPCWithConsumers,
 	tracer trace.Tracer,
 ) *SlashingParamsFetcher {
 	return &SlashingParamsFetcher{
 		Logger: logger.With().Str("component", "slashing_params_fetcher").Logger(),
 		Chains: chains,
 		RPCs:   rpcs,
 		Tracer: tracer,
+		queryInfos: make([]*types.QueryInfo, 0),
+		allParams: make(map[string]*types.SlashingParamsResponse),
 	}
 }
pkg/fetchers/consumer_info.go (1)

46-48: Consider documenting the purpose of empty Dependencies.

While the empty Dependencies implementation is valid, it would be helpful to document why this fetcher has no dependencies, especially since this is part of a new Controller architecture.

Add a comment explaining the independence of this fetcher:

 func (f *ConsumerInfoFetcher) Dependencies() []constants.FetcherName {
+    // ConsumerInfoFetcher operates independently and doesn't rely on data from other fetchers
     return []constants.FetcherName{}
 }
pkg/fetchers/consumer_validators.go (1)

46-48: Document the dependency pattern.

Similar to ConsumerInfoFetcher, consider documenting why this fetcher has no dependencies.

Add a clarifying comment:

 func (f *ConsumerValidatorsFetcher) Dependencies() []constants.FetcherName {
+    // ConsumerValidatorsFetcher operates independently of other fetchers
     return []constants.FetcherName{}
 }
pkg/fetchers/delegations.go (1)

40-42: Maintain consistent naming convention across fetchers.

The receiver variable is named q while other fetchers use f. Consider standardizing the naming convention.

Apply this change for consistency:

-func (q *DelegationsFetcher) Dependencies() []constants.FetcherName {
+func (f *DelegationsFetcher) Dependencies() []constants.FetcherName {
pkg/generators/active_set_tokens.go (1)

23-24: Consider enhancing error handling for state retrieval.

The current implementation silently returns empty collectors when state retrieval fails. Consider logging these failures to aid in debugging.

Add error logging:

 func (g *ActiveSetTokensGenerator) Generate(state statePkg.State) []prometheus.Collector {
     validators, ok := statePkg.StateGet[fetchersPkg.ValidatorsData](state, constants.FetcherNameValidators)
     if !ok {
+        g.Logger.Debug().Msg("Failed to retrieve validators data from state")
         return []prometheus.Collector{}
     }

     stakingParams, ok := statePkg.StateGet[fetchersPkg.StakingParamsData](state, constants.FetcherNameStakingParams)
     if !ok {
+        g.Logger.Debug().Msg("Failed to retrieve staking params from state")
         return []prometheus.Collector{}
     }

Also applies to: 29-31

pkg/fetchers/rewards.go (1)

47-47: Document the purpose of variadic parameters

The data ...interface{} parameter is added but not used in the implementation. Consider adding a comment explaining its intended future use or remove if not needed.

pkg/fetchers/consumer_commission.go (1)

51-51: Consider documenting the expected data parameters.

While the variadic parameter provides flexibility, it's currently unused. Consider adding a comment to document what types of data this fetcher might accept in the future.

pkg/fetchers/self_delegation.go (1)

47-47: Document the expected data parameters.

Similar to other fetchers, consider documenting the expected types for the variadic parameter.

pkg/generators/validator_commission_rate.go (1)

Line range hint 87-91: Consider adding error logging for missing consumer validators.

While the code handles missing data gracefully, consider adding debug-level logging when consumer validators data is not found to aid in troubleshooting.

 consumerValidators, ok := consumerCommissions.Commissions[consumer.Name]
 if !ok {
+    g.Logger.Debug().
+        Str("chain", consumer.Name).
+        Msg("No consumer validators found")
     continue
 }
pkg/fetchers/balance.go (1)

53-53: Consider documenting the expected data parameters.

The variadic parameter data ...interface{} is added but not used. Consider adding documentation about its purpose or expected usage in future implementations.

pkg/fetchers/price.go (1)

57-57: Consider documenting the expected data parameters.

The variadic parameter data ...interface{} is added but not used. Consider adding documentation about its purpose or expected usage in future implementations.

pkg/generators/validator_commission_rate_test.go (1)

31-31: Consider documenting the new Controller architecture.

The changes introduce a significant architectural shift towards a Controller-based fetching mechanism with explicit dependency management. Consider adding architecture documentation to help future contributors understand:

  1. The role of the Controller
  2. How fetchers interact with the Controller
  3. The new state management pattern
  4. The purpose of the variadic parameters in Fetch methods
pkg/app.go (1)

46-46: Consider renaming the Controller field for clarity

The field name Controller in the App struct may be too generic. Renaming it to something more specific like FetchController or DataController can improve code readability and make the purpose of the field clearer.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa542a9 and 64be568.

📒 Files selected for processing (70)
  • pkg/app.go (5 hunks)
  • pkg/controller/controller.go (1 hunks)
  • pkg/controller/controller_test.go (1 hunks)
  • pkg/fetchers/balance.go (1 hunks)
  • pkg/fetchers/commission.go (1 hunks)
  • pkg/fetchers/consumer_commission.go (1 hunks)
  • pkg/fetchers/consumer_info.go (1 hunks)
  • pkg/fetchers/consumer_validators.go (1 hunks)
  • pkg/fetchers/delegations.go (1 hunks)
  • pkg/fetchers/fetcher.go (1 hunks)
  • pkg/fetchers/has_to_validate.go (1 hunks)
  • pkg/fetchers/inflation.go (1 hunks)
  • pkg/fetchers/node_info.go (1 hunks)
  • pkg/fetchers/price.go (1 hunks)
  • pkg/fetchers/rewards.go (1 hunks)
  • pkg/fetchers/self_delegation.go (1 hunks)
  • pkg/fetchers/signing_info.go (1 hunks)
  • pkg/fetchers/slashing_params.go (1 hunks)
  • pkg/fetchers/staking_params.go (1 hunks)
  • pkg/fetchers/supply.go (1 hunks)
  • pkg/fetchers/unbonds.go (1 hunks)
  • pkg/fetchers/validators.go (1 hunks)
  • pkg/generators/active_set_tokens.go (1 hunks)
  • pkg/generators/active_set_tokens_test.go (8 hunks)
  • pkg/generators/balance.go (1 hunks)
  • pkg/generators/balance_test.go (2 hunks)
  • pkg/generators/commission.go (1 hunks)
  • pkg/generators/commission_test.go (2 hunks)
  • pkg/generators/consumer_info.go (1 hunks)
  • pkg/generators/consumer_info_test.go (2 hunks)
  • pkg/generators/consumer_needs_to_sign.go (1 hunks)
  • pkg/generators/consumer_needs_to_sign_test.go (3 hunks)
  • pkg/generators/delegations.go (1 hunks)
  • pkg/generators/delegations_test.go (2 hunks)
  • pkg/generators/generator.go (1 hunks)
  • pkg/generators/inflation.go (1 hunks)
  • pkg/generators/inflation_test.go (2 hunks)
  • pkg/generators/is_consumer.go (1 hunks)
  • pkg/generators/is_consumer_test.go (1 hunks)
  • pkg/generators/node_info.go (1 hunks)
  • pkg/generators/node_info_test.go (2 hunks)
  • pkg/generators/price.go (1 hunks)
  • pkg/generators/price_test.go (2 hunks)
  • pkg/generators/rewards.go (1 hunks)
  • pkg/generators/rewards_test.go (2 hunks)
  • pkg/generators/self_delegation.go (1 hunks)
  • pkg/generators/self_delegations_test.go (2 hunks)
  • pkg/generators/signing_info.go (1 hunks)
  • pkg/generators/signing_info_test.go (2 hunks)
  • pkg/generators/single_validator_info.go (1 hunks)
  • pkg/generators/single_validator_info_test.go (5 hunks)
  • pkg/generators/slashing_params.go (1 hunks)
  • pkg/generators/slashing_params_test.go (2 hunks)
  • pkg/generators/staking_params.go (1 hunks)
  • pkg/generators/staking_params_test.go (2 hunks)
  • pkg/generators/supply.go (1 hunks)
  • pkg/generators/supply_test.go (2 hunks)
  • pkg/generators/unbonds.go (1 hunks)
  • pkg/generators/unbonds_test.go (2 hunks)
  • pkg/generators/uptime.go (1 hunks)
  • pkg/generators/uptime_test.go (1 hunks)
  • pkg/generators/validator_active.go (3 hunks)
  • pkg/generators/validator_active_test.go (6 hunks)
  • pkg/generators/validator_commission_rate.go (2 hunks)
  • pkg/generators/validator_commission_rate_test.go (4 hunks)
  • pkg/generators/validator_rank.go (1 hunks)
  • pkg/generators/validator_rank_test.go (5 hunks)
  • pkg/generators/validators_info.go (1 hunks)
  • pkg/generators/validators_info_test.go (5 hunks)
  • pkg/state/state.go (1 hunks)
🧰 Additional context used
📓 Learnings (3)
pkg/generators/validators_info.go (1)
Learnt from: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#63
File: pkg/fetchers/consumer_validators.go:40-40
Timestamp: 2024-11-12T12:10:19.288Z
Learning: The `TestConsumerValidatorsFetcherBase` method in `pkg/fetchers/consumer_validators_test.go` tests the initialization of `ConsumerValidatorsFetcher` with the `Chains` parameter.
pkg/generators/validator_commission_rate.go (1)
Learnt from: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#63
File: pkg/fetchers/consumer_validators.go:40-40
Timestamp: 2024-11-12T12:10:19.288Z
Learning: The `TestConsumerValidatorsFetcherBase` method in `pkg/fetchers/consumer_validators_test.go` tests the initialization of `ConsumerValidatorsFetcher` with the `Chains` parameter.
pkg/generators/validator_active.go (1)
Learnt from: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#63
File: pkg/fetchers/consumer_validators.go:40-40
Timestamp: 2024-11-12T12:10:19.288Z
Learning: The `TestConsumerValidatorsFetcherBase` method in `pkg/fetchers/consumer_validators_test.go` tests the initialization of `ConsumerValidatorsFetcher` with the `Chains` parameter.
🪛 GitHub Check: codecov/patch
pkg/state/state.go

[warning] 15-15: pkg/state/state.go#L15
Added line #L15 was not covered by tests


[warning] 40-41: pkg/state/state.go#L40-L41
Added lines #L40 - L41 were not covered by tests


[warning] 45-49: pkg/state/state.go#L45-L49
Added lines #L45 - L49 were not covered by tests


[warning] 53-54: pkg/state/state.go#L53-L54
Added lines #L53 - L54 were not covered by tests

pkg/controller/controller.go

[warning] 88-91: pkg/controller/controller.go#L88-L91
Added lines #L88 - L91 were not covered by tests


[warning] 95-98: pkg/controller/controller.go#L95-L98
Added lines #L95 - L98 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint
🔇 Additional comments (56)
pkg/fetchers/has_to_validate.go (1)

46-48: LGTM! Clean implementation of dependency declaration.

The empty dependency list correctly indicates that this fetcher operates independently.

pkg/generators/commission.go (1)

20-20: Passing State by value instead of pointer

The Generate method now accepts state by value rather than by pointer. Since maps in Go are reference types, passing a map by value does not copy the underlying data. This change simplifies the function signature without affecting performance.

pkg/generators/balance.go (1)

20-20: Passing State by value instead of pointer

The Generate method now accepts state by value rather than by pointer. As maps are reference types in Go, this change does not create a copy of the map and maintains efficient memory usage.

pkg/generators/validators_info.go (1)

24-28: Refactoring enhances type safety and simplifies data retrieval

The use of the generic statePkg.StateGet function with type parameters improves type safety and eliminates the need for type assertions. This refactoring enhances code readability and maintainability.

pkg/generators/generator.go (1)

10-10: Consider performance implications of passing State by value.

While passing by value ensures immutability, consider the size of the State struct. If it's large, passing by pointer might be more efficient. Could you clarify the rationale behind this change?

Let's check the size of the State struct:

pkg/generators/uptime_test.go (1)

16-16: Verify state initialization requirements.

The change from NewState() to State{} suggests the removal of a constructor. Ensure that:

  1. No default values are required for the state
  2. All generators handle an empty state gracefully

Let's check for other test files that might provide insights:

✅ Verification successful

Empty state initialization is the correct pattern

The consistent usage across all test files confirms that State{} is the intended initialization pattern, with state being explicitly populated using Set() when needed. All generators properly handle empty state initialization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all test files using State initialization
rg -l "NewState\(\)" --type go

Length of output: 32


Script:

#!/bin/bash
# Find State struct definition
ast-grep --pattern 'type State struct {
  $$$
}'

# Find test files using State
rg -l "statePkg\.State" --type go

# Look for State initialization patterns in test files
rg "state\s*:=\s*statePkg\.State" --type go -A 2

Length of output: 18574

pkg/fetchers/fetcher.go (1)

15-35: LGTM! Well-structured utility type.

The Fetchers type and its methods are well-designed:

  • Clear separation of concerns
  • Efficient implementation using make
  • Useful string conversion utility
pkg/generators/is_consumer_test.go (1)

17-17: Verify state initialization compatibility

The change from NewState() to direct struct initialization suggests a simplified state type. Ensure this change is compatible with all state operations and doesn't skip any necessary initialization logic that was previously in NewState().

✅ Verification successful

Direct state initialization is correct

The change from NewState() to direct struct initialization is valid as State is a simple map type that doesn't require special initialization logic. The type's methods handle all necessary safety checks and conversions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining NewState() calls that might need similar updates
rg "NewState\(\)" --type go

# Look for any custom initialization logic in the old NewState function
rg "func NewState" --type go

Length of output: 60


Script:

#!/bin/bash
# Find the state package location and structure
fd "state" --type d

# Look for state struct definition and initialization patterns
rg "type State struct" --type go -A 5

# Check for any constructor patterns in state-related files
ast-grep --pattern 'func New$_($$$) *state.$_ {'

Length of output: 121


Script:

#!/bin/bash
# Examine state package content
cat pkg/state/*.go

# Look for any state-related tests that might show initialization patterns
cat pkg/state/*_test.go 2>/dev/null

Length of output: 1127

pkg/generators/is_consumer.go (1)

19-19: LGTM! Parameter type change is consistent

The update to use value-based state parameter aligns with the architectural changes and maintains the existing functionality.

pkg/generators/staking_params.go (1)

18-19: LGTM! Clean transition to the new state management approach.

The changes align well with the architectural improvements:

  1. Moving to value semantics for state parameter improves clarity
  2. Using StateGet with type parameter enhances type safety
pkg/generators/unbonds_test.go (1)

18-18: Verify state initialization behavior.

The transition from NewState() to direct struct initialization (State{}) might skip important default initializations. Please ensure that:

  1. The empty state initialization provides all necessary default values
  2. No initialization logic from the removed NewState() function needs to be preserved

Also applies to: 27-27

✅ Verification successful

Empty state initialization is correct and safe.

The codebase consistently shows that State is a simple data container where all required data is explicitly set using state.Set(). The transition from NewState() to State{} maintains the expected behavior as no default initialization is required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any default initialization in the old NewState implementation
rg -l "func NewState" | xargs rg "func NewState[^a-zA-Z]" -A 10

Length of output: 65


Script:

#!/bin/bash
# Find and examine State struct definition
ast-grep --pattern 'type State struct {
  $$$
}'

# Look for documentation about state initialization
fd README.md | xargs rg -i "state.*initialization"

# Check how State is used in tests
rg "State{.*}" -A 2

Length of output: 223


Script:

#!/bin/bash
# Find State struct definition and usage in state package
fd -e go | xargs rg "type State struct" -A 5

# Check State initialization patterns in tests
rg "State\{" -A 2

# Look for any state-related constructor patterns
rg "New.*State"

Length of output: 17087

pkg/generators/inflation_test.go (1)

20-20: Similar state initialization changes as in unbonds_test.go

The same considerations about state initialization apply here.

Also applies to: 29-29

pkg/generators/delegations.go (1)

18-19: LGTM! Consistent with the new architecture.

The changes follow the same pattern as other generators:

  1. Value semantics for state
  2. Type-safe data retrieval with StateGet
pkg/generators/delegations_test.go (1)

18-18: LGTM! Verify state initialization changes across the codebase.

The change from NewState() to State{} initialization aligns with the architectural shift to map-based state management.

Let's verify the consistency of this change across other test files:

Also applies to: 27-27

✅ Verification successful

✅ State initialization is consistent across the codebase

All test files consistently use statePkg.State{} initialization, aligning with the map-based state implementation. No legacy constructor calls remain.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining NewState() calls that might need updating
rg "NewState\(\)" "pkg/generators" -l

Length of output: 37


Script:

#!/bin/bash
# First, find all state-related files
fd "state.*\.go" 

# Then search for various state initialization patterns with context
rg "state\s*:=\s*(?:statePkg\.)?State{" -p --context 2
rg "state\s*=\s*(?:statePkg\.)?State{" -p --context 2

# Also check for any other state-related constructor patterns
rg "New.*State" -p --context 2

Length of output: 445


Script:

#!/bin/bash
# Check state.go content
cat pkg/state/state.go

# Search with corrected patterns
rg "state\s*:=\s*statePkg\.State\{" --type go
rg "state\s*=\s*statePkg\.State\{" --type go
rg "state\s*:=\s*State\{" --type go
rg "state\s*=\s*State\{" --type go

# Look for any remaining constructor patterns
rg "NewState" --type go

Length of output: 5538

pkg/generators/price.go (1)

18-19: LGTM! Improved type safety with generic StateGet.

The changes bring two key improvements:

  1. Moving to value-based state parameter suggests immutable state handling
  2. Using StateGet with type parameters eliminates runtime type assertions
pkg/generators/staking_params_test.go (1)

19-19: Changes consistent with new state management approach.

Also applies to: 28-28

pkg/generators/signing_info.go (1)

18-19: Changes align with the new type-safe state management approach.

pkg/generators/slashing_params_test.go (1)

21-21: Verify state initialization behavior

The transition from NewState() to direct struct initialization (statePkg.State{}) aligns with the architectural changes. However, we should verify that this doesn't skip any necessary state initialization that might have been present in the constructor.

Also applies to: 30-30

✅ Verification successful

Direct State initialization is correct

The change to statePkg.State{} is valid as State is a simple map type that doesn't require special initialization. This pattern is consistently used across the codebase, including in the controller and all test files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any initialization logic in the old NewState constructor
rg -l "func NewState" pkg/state/

Length of output: 34


Script:

#!/bin/bash
# Find all state-related files
fd "state" --type f

# Look for State struct definition and usage patterns
rg "type State struct" -A 5
rg "State{}" -B 2 -A 2

# Check test files for similar state initialization patterns
rg "State{}" --type test

Length of output: 312


Script:

#!/bin/bash
# Check State struct definition
cat pkg/state/state.go

# Look for state initialization patterns in tests with escaped braces
rg -t go "State\{" pkg/
rg -t go "New.*State" pkg/

Length of output: 5454

pkg/generators/signing_info_test.go (1)

21-21: State initialization changes consistent with new architecture

The changes follow the same pattern as other test files, transitioning to the new state management approach.

Also applies to: 30-30

pkg/generators/price_test.go (1)

18-18: LGTM - Consistent with architectural changes

Changes align with the new state management approach seen across other files.

Also applies to: 27-27

pkg/generators/node_info.go (1)

18-19: Improved type safety and efficiency in state handling

Good improvements:

  1. Using value-based state parameter instead of pointer
  2. Leveraging type-safe StateGet generic function
  3. Removing manual type assertion

Let's verify this pattern is consistently applied across other generators.

✅ Verification successful

✅ Verified: Consistent type-safe state handling across all generators

The improvements have been consistently implemented across all generators in the codebase:

  • All generators use the type-safe StateGet pattern
  • No pointer-based state parameters remain
  • Proper error handling is maintained throughout
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent usage of StateGet across generators
rg "StateGet\[.*\]" pkg/generators/
# Check for any remaining pointer-based state parameters
rg "Generate\(.*\*statePkg\.State\)" pkg/generators/

Length of output: 3696

pkg/generators/rewards.go (1)

20-21: LGTM! Type-safe state access improvements

The changes improve type safety by:

  1. Making state immutable through value-based parameter
  2. Using generic StateGet for compile-time type checking
pkg/generators/self_delegation.go (1)

20-21: LGTM! Consistent implementation of type-safe state access

The changes follow the same pattern of improved type safety through immutable state and generic type checking.

pkg/generators/supply.go (1)

20-21: LGTM! Type safety particularly valuable for complex data structures

The generic state access is especially beneficial here, providing compile-time guarantees for the nested supply data structure.

pkg/fetchers/validators.go (1)

46-46: Verify the need for unused variadic parameter

The data ...interface{} parameter is added but not used in the implementation. If this is part of a standardized interface for the Controller architecture, consider documenting this intent.

Let's check if other fetchers follow the same pattern:

✅ Verification successful

The variadic parameter is required by the Fetcher interface

The data ...interface{} parameter is part of the Fetcher interface contract defined in pkg/fetchers/fetcher.go. While not used in this specific implementation, it must be present to satisfy the interface.

Consider adding a comment to document that this parameter is part of the interface contract:

// Fetch implements the Fetcher interface
func (f *ValidatorsFetcher) Fetch(
    ctx context.Context,
    data ...interface{}, // Required by Fetcher interface
) (interface{}, []*types.QueryInfo) {
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Fetch method implementations across fetchers
ast-grep --pattern 'func $_($_, data ...interface{}) (interface{}, $_) {
  $$$
}'

Length of output: 83


Script:

#!/bin/bash
# Search for Fetch method declarations and interfaces
echo "=== Fetch method declarations ==="
rg "func.*Fetch.*\(.*\).*\(" -A 2

echo -e "\n=== Interface definitions with Fetch ==="
rg "type.*interface.*{" -A 5 -B 1 | rg -A 5 -B 1 "Fetch"

Length of output: 541


Script:

#!/bin/bash
# Search for interface definitions and validator implementation
echo "=== Interface definitions ==="
rg "type.*interface" -A 5 | rg -A 5 "Fetch"

echo -e "\n=== Validator implementation ==="
cat pkg/fetchers/validators.go

Length of output: 3113

pkg/generators/commission_test.go (1)

22-22: LGTM! State initialization aligns with new architecture

The change from NewState() to direct State{} initialization is consistent with the architectural changes moving from a struct-based to a map-based state implementation.

Also applies to: 31-31

pkg/generators/self_delegations_test.go (1)

22-22: LGTM! Consistent state initialization changes

The state initialization changes align with the new map-based state implementation and are consistent with other test files.

Also applies to: 31-31

pkg/fetchers/commission.go (1)

45-46: Document or utilize the variadic parameter.

The data parameter is added but not used. Consider either:

  1. Adding documentation explaining its future use, or
  2. Utilizing it if there's relevant data that could be passed from the controller

Let's check if other fetchers use this parameter:

✅ Verification successful

Add documentation to explain the interface's extensibility design

The data ...interface{} parameter is part of a consistent interface pattern implemented across all fetchers. While currently unused, it appears to be designed for future extensibility. Add a comment explaining this design choice:

// Fetch retrieves commission data. The variadic data parameter is reserved for future
// interface extensibility and is currently unused.
func (q *CommissionFetcher) Fetch(
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any usage of the variadic parameter in fetchers
rg -U "func.*Fetch.*data \.\.\." pkg/fetchers/ -A 5 | rg "data\["

Length of output: 67


Script:

#!/bin/bash
# Get all Fetch function declarations in fetchers
echo "=== Fetch function declarations with variadic parameters ==="
rg -U "func.*Fetch.*\.\.\." pkg/fetchers/

echo -e "\n=== Commission fetcher implementation ==="
cat pkg/fetchers/commission.go

echo -e "\n=== Any usage of 'data' parameter in fetchers ==="
rg "data\W" pkg/fetchers/ --type go

Length of output: 19626

pkg/generators/consumer_info_test.go (1)

22-22: Verify removal of NewState constructor.

The change from NewState() to State{} suggests the constructor might have been removed. Let's verify this change is consistent across the codebase.

Also applies to: 31-31

✅ Verification successful

Constructor removal verified and consistent

The codebase shows consistent usage of State{} initialization across all files, with no remaining instances of NewState(). The change is properly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if NewState is still used elsewhere
rg "NewState\(\)" pkg/
# Check if State{} initialization is used consistently
rg "State\{\}" pkg/

Length of output: 4346

pkg/generators/active_set_tokens.go (1)

23-23: Verify state immutability requirements.

The change from pointer to value type for the state parameter suggests a move towards immutable state. Let's verify this pattern across the codebase.

pkg/generators/consumer_info.go (1)

22-23: Great improvements to type safety and state handling!

The changes improve the code in two ways:

  1. Using statePkg.StateGet with type parameter provides compile-time type safety
  2. Taking state by value enforces immutability in generators
pkg/generators/supply_test.go (1)

22-22: LGTM! Clean transition to direct state initialization

The change from NewState() to direct struct initialization State{} aligns well with the new map-based state implementation while maintaining test coverage.

Also applies to: 31-31

pkg/fetchers/rewards.go (1)

41-43: Verify if rewards fetcher has dependencies

The Dependencies() method returns an empty slice, but rewards calculation typically depends on validator information. Consider if constants.FetcherNameValidators should be included as a dependency.

pkg/generators/validator_rank.go (1)

32-33: LGTM! Consistent with other generators

The changes align with the codebase-wide improvements:

  1. Immutable state handling
  2. Type-safe data retrieval with StateGet

The complex validator ranking logic remains well-maintained.

pkg/fetchers/consumer_commission.go (1)

46-48: LGTM! Dependencies method implementation looks correct.

The empty slice return is appropriate as this fetcher operates independently.

pkg/fetchers/self_delegation.go (1)

41-43: LGTM! Dependencies implementation is consistent.

The empty dependencies implementation aligns with other fetchers.

pkg/generators/balance_test.go (1)

22-22: LGTM! State initialization simplified.

The direct state initialization is cleaner and removes unnecessary constructor calls.

Also applies to: 31-31

pkg/generators/validator_commission_rate.go (2)

31-31: LGTM! State parameter changed to value type.

This change aligns with the new state management approach and is more idiomatic.


32-40: Improved type safety with generic StateGet.

The use of generic StateGet function provides better type safety and eliminates the need for type assertions.

pkg/generators/validator_active.go (2)

31-31: LGTM! State parameter change and data retrieval updates.

The changes align with the new state management approach, using value semantics instead of pointers and the new StateGet function for type-safe data retrieval.

Also applies to: 37-37


51-51: Verify error handling in map access.

The code accesses nested maps (validators.Validators[chain.Name] and allConsumerValidators.Validators[consumer.Name]) without checking if the top-level maps are initialized.

Also applies to: 94-94

pkg/fetchers/balance.go (1)

47-49: LGTM! Added Dependencies method.

The empty dependency list is appropriate as this fetcher operates independently.

pkg/fetchers/price.go (1)

51-53: LGTM! Added Dependencies method.

The empty dependency list is appropriate as the price fetcher operates independently.

pkg/generators/validator_commission_rate_test.go (1)

22-22: LGTM! Updated state initialization.

The change from NewState() to direct struct initialization State{} aligns with the new state management approach. The test coverage remains comprehensive.

Also applies to: 32-32, 49-49, 85-85

pkg/generators/single_validator_info.go (1)

31-32: LGTM: Type-safe state retrieval implementation.

The change to use StateGet with type parameters improves type safety by eliminating the need for type assertions.

pkg/generators/validator_rank_test.go (1)

22-22: LGTM: Consistent state initialization across test cases.

The change to use direct state initialization with statePkg.State{} simplifies the test setup and aligns with the new state implementation.

Also applies to: 32-32, 44-44, 60-60, 84-84, 123-123, 162-162

pkg/fetchers/signing_info.go (2)

47-49: LGTM: Clear dependency declaration.

The Dependencies method explicitly declares that this fetcher has no dependencies on other fetchers.


51-54: Verify error handling for variadic parameters.

The Fetch method now accepts variadic parameters but doesn't seem to use them. Ensure this aligns with the fetcher interface requirements and consider documenting the expected parameters if any.

pkg/generators/active_set_tokens_test.go (1)

24-24: LGTM: Consistent state initialization pattern.

The state initialization changes align with the new state management approach seen across other test files.

Also applies to: 33-33, 44-44, 60-60, 84-84, 123-123, 162-162

pkg/generators/validator_active_test.go (1)

22-22: Verify state initialization changes across test cases.

The change from NewState() to State{} appears in multiple test cases. While this aligns with the state management refactor, we should verify that no critical initialization logic from NewState() is being lost.

Also applies to: 32-32, 43-43, 62-62, 93-93, 141-141

✅ Verification successful

State{} initialization is safe and correct

The State type is a simple map type alias (map[constants.FetcherName]interface{}), and State{} properly initializes an empty map. The codebase shows that all state operations (Get, Set, GetData) handle empty/nil cases appropriately, so no critical initialization logic is being lost in this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any special initialization in NewState
rg -A 5 "func NewState" 

Length of output: 25


Script:

#!/bin/bash
# Find state package directory
fd -t d state

# Look for NewState function and State struct definition
ast-grep --pattern 'func NewState() $$$'
ast-grep --pattern 'type State struct { $$$ }'

# Backup search with ripgrep for any State-related code
rg "type State struct|func NewState" -A 5

Length of output: 162


Script:

#!/bin/bash
# Check all files in the state package
cat pkg/state/*.go

# Specific search for State-related code in the state package
rg "type State|func NewState|State{}" pkg/state/ -A 5

Length of output: 1301

pkg/generators/single_validator_info_test.go (1)

24-24: State initialization changes noted.

Similar changes to state initialization as in validator_active_test.go.

Also applies to: 34-34, 52-52, 84-84, 177-177

pkg/generators/unbonds.go (1)

18-19: Great improvements to type safety!

The changes enhance the code in several ways:

  1. Using StateGet with generics eliminates runtime type assertions
  2. Passing state by value is safe as maps are reference types
  3. The code is now more idiomatic Go
pkg/generators/node_info_test.go (1)

19-19: State initialization changes noted.

Similar changes to state initialization as in other test files.

Also applies to: 28-28

pkg/generators/rewards_test.go (1)

22-22: State initialization changes align with the new architecture

The changes from NewState() to direct struct initialization align with the architectural shift to map-based state management. The test behavior remains unchanged.

Let's verify test coverage for the new state management approach:

Also applies to: 31-31

✅ Verification successful

State initialization changes are consistently applied across all test files

The migration from NewState() to State{} initialization is complete and uniform across all 22 test files in the generators package, with no remnants of the old pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for state management
# Look for any potentially uncovered edge cases in state initialization

# Search for all state initialization patterns
rg -p "state\s*:=\s*statePkg\.State\{" --type go

# Look for any remaining old initialization patterns that might have been missed
rg -p "state\s*:=\s*statePkg\.NewState\(\)" --type go

Length of output: 2924

pkg/generators/consumer_needs_to_sign_test.go (1)

20-20: Verify state management with complex nested data structures

The state initialization changes are consistent. However, let's verify that the new map-based state management properly handles complex nested data structures used in these tests.

Run this script to analyze the data structure handling:

Also applies to: 29-29, 48-48

✅ Verification successful

State management properly handles complex data structures

The state initialization changes are safe and properly handle all complex nested data structures used in the tests, including nested maps, structs, and arrays. The implementation is consistent across all test files with no type conversion issues or data structure mismatches.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify state management with complex data structures
# Look for potential type conversion issues or data structure mismatches

# Search for all Set operations with complex data structures
rg -p "state\.Set.*map\[string\]" --type go -A 5

# Look for any type assertions or conversions that might indicate issues
ast-grep --pattern 'state.Set($_, $_)'

Length of output: 42061

pkg/generators/validators_info_test.go (1)

23-23: Verify decimal handling in the new state management

The state initialization changes are consistent. Given the use of math.LegacyMustNewDecFromStr for decimal operations in these tests, we should verify that the new map-based state management properly handles decimal values.

Run this script to analyze decimal handling:

Also applies to: 32-32, 42-42, 93-93, 141-141

✅ Verification successful

Decimal handling is safe in the new state management

The verification shows that decimal values are only used as input data and passed through to metrics without transformations. The map-based state acts as a simple storage mechanism without performing any operations that could affect decimal precision.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify decimal value handling in state management
# Look for potential precision loss or type conversion issues

# Search for decimal operations in test files
rg -p "LegacyMustNewDecFromStr.*state\." --type go -A 5

# Look for any type conversions involving decimal values
ast-grep --pattern 'math.LegacyMustNewDecFromStr($_, $_)'

Length of output: 117


Script:

#!/bin/bash
# Search for all decimal operations in test files
echo "=== Decimal Operations in Tests ==="
rg "LegacyMustNewDecFromStr" --type go -B 2 -A 2

# Search for state usage patterns
echo -e "\n=== State Usage Patterns ==="
rg "state\." --type go -B 1 -A 1

# Look for type declarations
echo -e "\n=== Type Declarations ==="
ast-grep --pattern 'type $_ struct {
  $$$
}'

# Search specifically in the test file
echo -e "\n=== Test File Content ==="
cat pkg/generators/validators_info_test.go

Length of output: 68022

pkg/state/state.go Show resolved Hide resolved
pkg/state/state.go Outdated Show resolved Hide resolved
pkg/controller/controller.go Show resolved Hide resolved
pkg/controller/controller_test.go Outdated Show resolved Hide resolved
pkg/fetchers/consumer_info.go Show resolved Hide resolved
pkg/app.go Show resolved Hide resolved
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: 0

🧹 Nitpick comments (3)
pkg/fetchers/stub.go (2)

9-24: Add documentation explaining the purpose of StubFetcher1

This appears to be a test double, but its purpose and usage scenarios should be documented. Consider adding comments explaining:

  • Why this stub exists
  • How it should be used in tests
  • What the nil return value represents

Additionally, consider enhancing the Fetch implementation to support configurable return values for better testing scenarios:

 type StubFetcher1 struct{}
+
+// TestResult holds the configurable return values for testing
+type TestResult struct {
+    Data interface{}
+    Queries []*types.QueryInfo
+}
+
+// NewStubFetcher1 creates a new StubFetcher1 with configurable test results
+func NewStubFetcher1(result TestResult) *StubFetcher1 {
+    return &StubFetcher1{result: result}
+}

26-41: Add documentation explaining the dependency relationship

The dependency relationship between StubFetcher2 and StubFetcher1 should be documented to clarify the testing scenarios this setup enables.

Consider enhancing the implementation to verify that the dependency's data is actually used:

 type StubFetcher2 struct{}
+
+// Fetch demonstrates proper dependency data usage
 func (f *StubFetcher2) Fetch(
 	ctx context.Context,
 	data ...interface{},
 ) (interface{}, []*types.QueryInfo) {
+    if len(data) == 0 {
+        return nil, []*types.QueryInfo{}
+    }
+    
+    // Verify and use StubFetcher1's data
+    if stub1Data := data[0]; stub1Data != nil {
+        // Process dependent data
+        return stub1Data, []*types.QueryInfo{}
+    }
 	return nil, []*types.QueryInfo{}
 }
pkg/constants/constants.go (1)

27-28: Consider moving test constants to a separate file

Since FetcherNameStub1 and FetcherNameStub2 are used for testing purposes, consider moving them to a separate test_constants.go file to maintain a clear separation between production and test code.

// test_constants.go
package constants

const (
    FetcherNameStub1 FetcherName = "stub1"
    FetcherNameStub2 FetcherName = "stub2"
)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64be568 and e9653c4.

📒 Files selected for processing (4)
  • pkg/constants/constants.go (1 hunks)
  • pkg/controller/controller_test.go (1 hunks)
  • pkg/fetchers/stub.go (1 hunks)
  • pkg/fetchers/supply.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/controller/controller_test.go
🔇 Additional comments (3)
pkg/fetchers/supply.go (3)

39-39: Fixed logger component name.

The component name in the logger has been correctly updated from "balance_fetcher" to "supply_fetcher" to accurately reflect its purpose.


46-48: LGTM: Dependencies implementation is correct.

The empty dependency list is appropriate as supply data can be fetched independently of other fetchers.


52-52: LGTM: Fetch signature update aligns with interface changes.

The addition of variadic parameters maintains backward compatibility while providing flexibility for future extensions.

Let's verify that this change is consistent across all fetchers:

✅ Verification successful

Fetch signature consistency verified across all fetchers

The variadic parameter addition is consistently implemented across all fetcher implementations in the codebase, maintaining backward compatibility as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all fetchers have been updated to use the new Fetch signature
# Expected: All fetchers should have the same signature pattern

ast-grep --pattern 'func ($_ *$_) Fetch(ctx context.Context, data ...interface{})'

Length of output: 43539

@freak12techno freak12techno merged commit c262e48 into main Jan 7, 2025
8 checks passed
@freak12techno freak12techno deleted the add-fetcher-controller branch January 7, 2025 17:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant