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

refactor(zetaclient): move app context update from zetacore client #3131

Merged
merged 10 commits into from
Nov 12, 2024

Conversation

swift1337
Copy link
Contributor

@swift1337 swift1337 commented Nov 8, 2024

Previously, zetacoreClient was a client that also handled background context updates and orchestrator shutdown, which was confusing. This PR refactors this behavior, making it only responsible for querying the node.

  • Decouple app context update from ZetaCore client
  • Move context updater into orchestrator package
  • Remove Stop() from ZetaCore client, effectively making it a client 🥁 rather than a stateful service
  • Simplify upgrade plan detection
  • Other minor tweaks

Closes #2589

Summary by CodeRabbit

Release Notes

  • New Features

    • Whitelisting SPL tokens on Solana.
    • Enhanced build reproducibility.
    • Integration of SPL deposits.
    • Concurrent withdrawal, deposit, and revert functionalities for TON blockchain.
    • Support for stateful precompiled contracts and enhancements to staking contracts.
  • Bug Fixes

    • Improved error handling for out-of-gas errors during omnichain calls.
    • Replaced public DHT with a private gossip peer discovery mechanism.
  • Refactor

    • Streamlined application context updates and error handling.
    • Removed unused code and improved logging practices.
  • Tests

    • Added unit tests for the UpdateAppContext function, covering successful updates and upgrade plan detection.

@swift1337 swift1337 self-assigned this Nov 8, 2024
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces multiple updates across various components of the ZetaChain node, including enhancements, refactoring, and fixes. Key features include the ability to whitelist SPL tokens on Solana, improvements in build reproducibility, and the integration of SPL deposits. The application context update mechanism has been centralized within the orchestrator, and several methods have been added or modified to streamline functionality. Additionally, the changelog has been updated to reflect these changes, alongside the transition to version 21.0.0.

Changes

File Path Change Summary
changelog.md Updated to include new features, improvements, and fixes; notable additions include SPL token whitelisting and enhancements to build reproducibility.
cmd/zetaclientd/inbound.go Modified InboundGetBallot to call orchestrator.UpdateAppContext instead of client.UpdateAppContext.
cmd/zetaclientd/start.go Refactored Start function to enhance clarity and modularity; improved error handling and logging.
cmd/zetaclientd/utils.go Added waitForZetacoreToCreateBlocks function for checking ZetaCore readiness.
pkg/rpc/clients.go Renamed NewGRPCClient to NewGRPCClients to reflect multiple client creation.
pkg/rpc/clients_cosmos.go Changed return type of GetUpgradePlan from pointer to value; improved error handling.
zetaclient/chains/interfaces/interfaces.go Added new methods to ZetacoreClient interface; removed Stop() method.
zetaclient/orchestrator/contextupdater.go Introduced functionality for managing application context updates; added new methods and error handling.
zetaclient/orchestrator/contextupdater_test.go Added unit tests for UpdateAppContext functionality.
zetaclient/orchestrator/orchestrator.go Added Stop() method; modified Start() and runObserverSignerSync() for improved lifecycle management.
zetaclient/testutils/mocks/zetacore_client.go Added mock methods for new ZetacoreClient methods; removed unnecessary methods.
zetaclient/zetacore/client.go Removed unused imports and methods related to client lifecycle management.
zetaclient/zetacore/client_worker.go Deleted file containing UpdateAppContextWorker function.
zetaclient/zetacore/constant.go Removed constants related to transaction broadcasting retries.
zetaclient/zetacore/tx_test.go Removed unused imports and the TestZetacore_UpdateAppContext function.

Assessment against linked issues

Objective Addressed Explanation
Move worker/async logic out of zetaclient/zetacore (2589)

Possibly related PRs

Suggested labels

no-changelog

Suggested reviewers

  • fbac
  • kingpinXD
  • skosito
  • brewmaster012
  • lumtis
  • ws4charlie
  • gartnera

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 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.

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.

@swift1337 swift1337 marked this pull request as ready for review November 8, 2024 15:16
@swift1337 swift1337 added the UPGRADE_LIGHT_TESTS Run make start-upgrade-test-light label Nov 8, 2024
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: 3

🧹 Outside diff range and nitpick comments (18)
pkg/rpc/clients_cosmos.go (1)

16-28: Clean refactoring of GetUpgradePlan method.

The changes improve the method in several ways:

  1. Returning a value type instead of a pointer eliminates nil pointer concerns
  2. Using switch for control flow makes the logic clearer
  3. Error wrapping provides better context for debugging

The implementation aligns well with the PR's objective of simplifying upgrade plan detection.

Consider documenting the error cases in the method comment to help API consumers handle different scenarios appropriately. For example:

// GetUpgradePlan returns the current upgrade plan.
// Returns empty plan if no upgrade is planned.
// Returns empty plan and error if failed to fetch the plan.
zetaclient/orchestrator/contextupdater_test.go (3)

16-24: Consider adding documentation for test data setup.

While the setup is clean, adding comments explaining the significance of the mock parameters (e.g., why 100 was chosen) would improve maintainability.

 func Test_UpdateAppContext(t *testing.T) {
+	// Mock chain parameters with block confirmation of 100 blocks
 	var (
 		eth       = chains.Ethereum
 		ethParams = mocks.MockChainParams(eth.ChainId, 100)

25-60: Enhance test coverage with additional assertions.

While the test successfully verifies the addition of new chains, consider:

  1. Verifying that mock methods were called with expected parameters
  2. Asserting the state of other context properties (e.g., crosschain flags, TSS)

Add these assertions after the existing checks:

 		require.NoError(t, err)
+		// Verify mock calls
+		zetacore.AssertCalled(t, "GetBlockHeight", mock.Anything)
+		zetacore.AssertCalled(t, "GetChainParams", mock.Anything)
+
+		// Verify context state
+		require.True(t, app.IsInboundEnabled())
+		require.True(t, app.IsOutboundEnabled())
+		require.Equal(t, "0x123", app.GetTSSKey())

61-82: Consider adding edge cases for upgrade plan detection.

The test effectively verifies basic upgrade detection, but consider adding test cases for:

  1. Upgrade plan at current height
  2. Upgrade plan far in the future
  3. Empty upgrade plan name

Example additional test case:

t.Run("Ignores distant upgrade plan", func(t *testing.T) {
    ctx := context.Background()
    app := createAppContext(t, eth, ethParams)
    zetacore := mocks.NewZetacoreClient(t)
    logger := zerolog.New(zerolog.NewTestWriter(t))

    zetacore.On("GetBlockHeight", mock.Anything).Return(int64(123), nil)
    zetacore.On("GetUpgradePlan", mock.Anything).Return(upgradetypes.Plan{
        Name:   "future",
        Height: 1000, // Far in the future
    }, nil)

    err := UpdateAppContext(ctx, app, zetacore, logger)
    require.NoError(t, err) // Should not trigger upgrade for distant plans
})
pkg/rpc/clients.go (1)

Line range hint 101-108: Function name change accurately reflects its behavior.

The rename from NewGRPCClient to NewGRPCClients better represents that the function creates multiple client interfaces. This aligns with the single responsibility principle and improves code clarity.

However, there are two areas for improvement:

  1. The gRPC connection should be managed to prevent resource leaks
  2. Error wrapping could be more descriptive for better debugging

Consider applying these improvements:

// NewGRPCClients creates a Clients which uses gRPC as the transport
func NewGRPCClients(url string, opts ...grpc.DialOption) (Clients, error) {
    grpcConn, err := grpc.Dial(url, opts...)
    if err != nil {
-       return Clients{}, err
+       return Clients{}, fmt.Errorf("failed to establish gRPC connection to %s: %w", url, err)
    }
+   // Store the connection in the Clients struct
+   clients, err := newClients(client.Context{}.WithGRPCClient(grpcConn))
+   if err != nil {
+       grpcConn.Close()
+       return Clients{}, fmt.Errorf("failed to initialize clients: %w", err)
+   }
-   clientCtx := client.Context{}.WithGRPCClient(grpcConn)
-   return newClients(clientCtx)
+   return clients, nil
}

Additionally, consider adding a Close() method to the Clients struct to properly clean up resources:

// Close closes all client connections and cleans up resources
func (c *Clients) Close() error {
    if conn := c.Auth.ClientConn(); conn != nil {
        return conn.Close()
    }
    return nil
}
cmd/zetaclientd/inbound.go (1)

Line range hint 46-196: Recommend restructuring for improved maintainability and error handling.

The InboundGetBallot function would benefit from several structural improvements:

  1. The argument validation is incorrect:
-cobra.ExactArgs(2)
+if err := cobra.ExactArgs(2)(cmd, args); err != nil {
+    return err
+}
  1. The function is quite long and handles multiple responsibilities. Consider breaking it down into smaller, focused functions:
func InboundGetBallot(cmd *cobra.Command, args []string) error {
    if err := cobra.ExactArgs(2)(cmd, args); err != nil {
        return err
    }
    
    ctx, client, appContext, err := setupContext(args)
    if err != nil {
        return err
    }
    
    ballotIdentifier, err := getBallotIdentifier(ctx, client, appContext, args)
    if err != nil {
        return err
    }
    
    return displayBallotInfo(ctx, client, ballotIdentifier)
}
  1. Chain-specific logic should be extracted to dedicated handlers:
type ChainHandler interface {
    GetBallotIdentifier(ctx context.Context, hash string) (string, error)
}

type EVMChainHandler struct {
    client zetacore.Client
    observer evmobserver.Observer
    // ... other dependencies
}

type BitcoinChainHandler struct {
    client zetacore.Client
    observer btcobserver.Observer
    // ... other dependencies
}

Would you like me to provide the complete refactoring implementation?

zetaclient/zetacore/client.go (2)

43-46: Consider improving struct field organization and documentation.

While the removal of stateful components aligns with the PR objectives, consider:

  1. Grouping related fields together (e.g., all configuration-related fields)
  2. Adding documentation for the fields to explain their purpose
 type Client struct {
 	zetacore_rpc.Clients
 	
+	// Configuration
 	config config.ClientConfiguration
+	encodingCfg etherminttypes.EncodingConfig
+	chainID     string
+	chain       chains.Chain
+
+	// Authentication
+	keys        keyinterfaces.ObserverKeys
 	cosmosClientContext cosmosclient.Context
 	
+	// State
 	blockHeight   int64
 	accountNumber map[authz.KeyType]uint64
 	seqNumber     map[authz.KeyType]uint64
 	
+	// Utilities
 	logger zerolog.Logger
 	mu sync.RWMutex
-	encodingCfg etherminttypes.EncodingConfig
-	keys        keyinterfaces.ObserverKeys
-	chainID     string
-	chain       chains.Chain
 }

Line range hint 234-235: Address TODO comment in SetAccountNumber method.

The TODO suggests this method should be part of the client constructor. This aligns with the PR's goal of making the client more stateless and predictable.

Would you like help refactoring this method into the constructor? This would involve:

  1. Moving the account number initialization logic to NewClient
  2. Removing the SetAccountNumber method
  3. Updating any existing callers
zetaclient/chains/interfaces/interfaces.go (1)

106-108: Add documentation to clarify chain types.

While the new methods follow good interface design patterns, the distinction between "Supported" and "Additional" chains needs clarification. Consider adding method documentation to explain:

  • What constitutes a supported chain vs. an additional chain
  • The relationship between these methods and GetChainParams
  • Usage guidelines for consumers of this interface

Example documentation:

// GetSupportedChains returns the list of primary chains supported by the system
// <add description of what makes a chain "supported">
GetSupportedChains(ctx context.Context) ([]chains.Chain, error)

// GetAdditionalChains returns secondary or auxiliary chains beyond the primary supported set
// <add description of what makes a chain "additional">
GetAdditionalChains(ctx context.Context) ([]chains.Chain, error)

// GetChainParams returns the configuration parameters for all chains
// <add description of relationship with supported/additional chains>
GetChainParams(ctx context.Context) ([]*observertypes.ChainParams, error)
zetaclient/zetacore/tx_test.go (1)

Line range hint 108-116: Consider enhancing error test coverage.

The commented-out test case for failed broadcast in TestZetacore_PostGasPrice could provide valuable negative test coverage. Consider:

  1. Re-implementing it with a shorter timeout
  2. Converting to table-driven tests to cover more error scenarios efficiently

Example refactor:

func TestZetacore_PostGasPrice(t *testing.T) {
    tests := []struct {
        name    string
        setup   func(*testing.T) *ZetaCoreClient
        wantErr bool
    }{
        {
            name: "success case",
            setup: func(t *testing.T) *ZetaCoreClient {
                return setupZetacoreClient(t,
                    withDefaultObserverKeys(),
                    withAccountRetriever(t, 100, 100),
                    withTendermint(mocks.NewSDKClientWithErr(t, nil, 0).SetBroadcastTxHash(sampleHash)),
                )
            },
            wantErr: false,
        },
        {
            name: "broadcast failure",
            setup: func(t *testing.T) *ZetaCoreClient {
                return setupZetacoreClient(t,
                    withDefaultObserverKeys(),
                    withAccountRetriever(t, 100, 100),
                    withTendermint(mocks.NewSDKClientWithErr(t, errors.New("broadcast error"), 0)),
                )
            },
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            client := tt.setup(t)
            hash, err := client.PostVoteGasPrice(context.Background(), chains.BscMainnet, 1000000, 0, 1234)
            if tt.wantErr {
                require.Error(t, err)
                require.Empty(t, hash)
            } else {
                require.NoError(t, err)
                require.Equal(t, sampleHash, hash)
            }
        })
    }
}
cmd/zetaclientd/start.go (1)

Line range hint 354-366: Enhance comment clarity for background configuration updates

The comment could be more specific about the nature and frequency of background configuration updates from ZetaCore.

Consider updating the comment to:

-// It also handles background configuration updates from zetacore
+// It also handles periodic background updates of chain configurations, parameters, and TSS information from ZetaCore
zetaclient/orchestrator/orchestrator.go (1)

142-144: Add documentation and consider thread safety

The Stop() method should include documentation explaining its purpose and behavior. Additionally, consider adding mutex protection to prevent potential race conditions during shutdown.

+// Stop gracefully shuts down the orchestrator by closing the stop channel.
+// This method is thread-safe and idempotent.
 func (oc *Orchestrator) Stop() {
+    oc.mu.Lock()
+    defer oc.mu.Unlock()
+    select {
+    case <-oc.stop:
+        // already closed
+        return
+    default:
         close(oc.stop)
+    }
 }
changelog.md (2)

17-17: Enhance the description of PR #3131.

The current description "move app context update from zetacore client" could be more detailed to better reflect the architectural changes and benefits. Consider adding more context about:

  • The move to the orchestrator package
  • The transformation of ZetaCore client into a stateless service
  • The improved separation of concerns
-* [3131](https://github.com/zeta-chain/node/pull/3131) - move app context update from zetacore client
+* [3131](https://github.com/zeta-chain/node/pull/3131) - refactor: move app context update from zetacore client to orchestrator, transforming ZetaCore client into a stateless service for improved separation of concerns

Line range hint 1-1000: Standardize category ordering across versions.

Consider maintaining a consistent order of categories across all versions. Suggested order:

  1. Breaking Changes
  2. Features
  3. Fixes
  4. Refactor
  5. Tests
  6. CI
  7. Docs
  8. Chores
zetaclient/orchestrator/contextupdater.go (4)

3-14: Replace github.com/pkg/errors with the standard library errors package

To reduce external dependencies and adhere to modern Go practices, consider replacing github.com/pkg/errors with Go's standard errors package, which provides error wrapping capabilities since Go 1.13.

Apply this diff to update the imports:

 import (
     "context"

     upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
-    "github.com/pkg/errors"
     "github.com/rs/zerolog"

     "github.com/zeta-chain/node/pkg/chains"
     "github.com/zeta-chain/node/pkg/ticker"
     observertypes "github.com/zeta-chain/node/x/observer/types"
     zctx "github.com/zeta-chain/node/zetaclient/context"
+    "errors"
 )

And modify error wrapping throughout the file using fmt.Errorf with %w. For example:

-    return errors.Wrap(err, "unable to get zeta block height")
+    return fmt.Errorf("unable to get zeta block height: %w", err)

Ensure all instances of errors.Wrap and errors.Wrapf are updated accordingly.


29-60: Separate the task function for clarity and maintainability

Consider extracting the anonymous task function within runAppContextUpdater into a named method. This enhances readability and allows for easier unit testing and potential reuse.

Apply this refactoring:

 func (oc *Orchestrator) runAppContextUpdater(ctx context.Context) error {
     app, err := zctx.FromContext(ctx)
     if err != nil {
         return err
     }

     interval := ticker.DurationFromUint64Seconds(app.Config().ConfigUpdateTicker)

     oc.logger.Info().Msg("UpdateAppContext worker started")

-    task := func(ctx context.Context, t *ticker.Ticker) error {
-        err := UpdateAppContext(ctx, app, oc.zetacoreClient, oc.logger.Sampled)
-        switch {
-        case errors.Is(err, ErrUpgradeRequired):
-            oc.onUpgradeDetected(err)
-            t.Stop()
-            return nil
-        case err != nil:
-            oc.logger.Err(err).Msg("UpdateAppContext failed")
-        }
-
-        return nil
-    }
+    // Extracted task function
+    return oc.updateAppContextTask(ctx, app, interval)
+
+}
+
+func (oc *Orchestrator) updateAppContextTask(ctx context.Context, app *zctx.AppContext, interval time.Duration) error {

     return ticker.Run(
         ctx,
         interval,
-        task,
+        func(ctx context.Context, t *ticker.Ticker) error {
+            err := UpdateAppContext(ctx, app, oc.zetacoreClient, oc.logger.Sampled)
+            switch {
+            case errors.Is(err, ErrUpgradeRequired):
+                oc.onUpgradeDetected(err)
+                t.Stop()
+                return nil
+            case err != nil:
+                oc.logger.Err(err).Msg("UpdateAppContext failed")
+            }
+
+            return nil
+        },
         ticker.WithLogger(oc.logger.Logger, "UpdateAppContext"),
         ticker.WithStopChan(oc.stop),
     )
 }

67-102: Use fmt.Errorf for error wrapping

Update error handling to use fmt.Errorf with the %w verb for error wrapping. This aligns with standard Go practices and improves error traceability.

For example, modify the error wrapping as follows:

-    return errors.Wrap(err, "unable to get zeta block height")
+    return fmt.Errorf("unable to get zeta block height: %w", err)

Apply similar changes to all error wrapping instances in the UpdateAppContext function.


152-153: Make upgradeRange a configurable parameter

Currently, upgradeRange is hard-coded to 2. Consider making upgradeRange a configurable parameter to provide flexibility and adjustability based on deployment needs.

Modify the code to read upgradeRange from the configuration:

 const (
-    upgradeRange = 2
 )
 
+upgradeRange := app.Config().UpgradeRange

Ensure that UpgradeRange is added to the application configuration with an appropriate default value.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 13cfffe and aedfc3f.

📒 Files selected for processing (15)
  • changelog.md (1 hunks)
  • cmd/zetaclientd/inbound.go (2 hunks)
  • cmd/zetaclientd/start.go (5 hunks)
  • cmd/zetaclientd/utils.go (3 hunks)
  • pkg/rpc/clients.go (1 hunks)
  • pkg/rpc/clients_cosmos.go (1 hunks)
  • zetaclient/chains/interfaces/interfaces.go (3 hunks)
  • zetaclient/orchestrator/contextupdater.go (1 hunks)
  • zetaclient/orchestrator/contextupdater_test.go (1 hunks)
  • zetaclient/orchestrator/orchestrator.go (2 hunks)
  • zetaclient/testutils/mocks/zetacore_client.go (5 hunks)
  • zetaclient/zetacore/client.go (3 hunks)
  • zetaclient/zetacore/client_worker.go (0 hunks)
  • zetaclient/zetacore/constant.go (0 hunks)
  • zetaclient/zetacore/tx_test.go (1 hunks)
💤 Files with no reviewable changes (2)
  • zetaclient/zetacore/client_worker.go
  • zetaclient/zetacore/constant.go
🧰 Additional context used
📓 Path-based instructions (12)
cmd/zetaclientd/inbound.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

cmd/zetaclientd/start.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

cmd/zetaclientd/utils.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/rpc/clients.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

pkg/rpc/clients_cosmos.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/chains/interfaces/interfaces.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/orchestrator/contextupdater.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/orchestrator/contextupdater_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/orchestrator/orchestrator.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/testutils/mocks/zetacore_client.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/zetacore/client.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

zetaclient/zetacore/tx_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🔇 Additional comments (21)
pkg/rpc/clients_cosmos.go (1)

15-16: Documentation improvement is clear and helpful.

The added comment clearly explains the empty plan return case, which is important for API consumers.

zetaclient/orchestrator/contextupdater_test.go (1)

1-14: LGTM: Well-organized imports and correct package declaration.

The imports are properly organized and the package name correctly matches the directory structure.

cmd/zetaclientd/utils.go (1)

4-4: LGTM: Import additions are appropriate.

The new imports support the context-aware operations and interface requirements for the new function.

Also applies to: 17-17

cmd/zetaclientd/inbound.go (2)

25-25: LGTM: Import addition aligns with refactoring goals.

The addition of the orchestrator package import supports the PR's objective of moving app context updates from zetacore client to orchestrator.


73-74: LGTM: Context update properly migrated to orchestrator.

The change successfully moves the app context update responsibility to the orchestrator package while maintaining proper error handling, aligning with the single-responsibility principle outlined in the PR objectives.

zetaclient/zetacore/client.go (1)

25-25: LGTM: Import changes align with stateless client design.

The addition of the logs package and removal of unused imports (context, time) aligns well with the PR's objective of transforming the client into a stateless component.

zetaclient/chains/interfaces/interfaces.go (2)

14-14: LGTM: Import aligns with new functionality.

The addition of the upgrade types import is necessary for the new GetUpgradePlan method's return type.


138-140: LGTM: Method changes align with refactoring goals.

The addition of GetUpgradePlan and reorganization of PostOutboundTracker support the transition to a stateless client design. Let's verify the implementation across the codebase.

✅ Verification successful

Let me verify the implementation of GetUpgradePlan since that's a key addition to the interface.


Method changes are properly implemented and integrated

The verification confirms:

  • GetUpgradePlan is correctly implemented in pkg/rpc/clients_cosmos.go using the upgrade module's CurrentPlan endpoint
  • The method is properly integrated into the context updater workflow in zetaclient/orchestrator/contextupdater.go
  • PostOutboundTracker relocation maintains interface consistency
  • Test coverage exists in pkg/rpc/clients_test.go
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of new methods and removal of Stop()

# Test 1: Check for complete implementation of new methods
echo "Checking implementation of new interface methods..."
rg -A 5 "func.*GetSupportedChains|func.*GetAdditionalChains|func.*GetChainParams|func.*GetUpgradePlan"

# Test 2: Verify Stop() method removal
echo "Verifying Stop() method removal..."
rg "func.*Stop\(\s*\)"

# Test 3: Check for any remaining direct app context updates
echo "Checking for direct app context updates..."
rg "zctx\.AppContext"

Length of output: 37734


Script:

#!/bin/bash
# Check implementation of GetUpgradePlan
echo "Checking GetUpgradePlan implementation..."
rg -A 5 "func.*GetUpgradePlan|GetCurrentPlan"

# Check usage of GetUpgradePlan
echo "Checking GetUpgradePlan usage..."
rg "GetUpgradePlan\("

Length of output: 2086

zetaclient/zetacore/tx_test.go (2)

Line range hint 1-1: Verify test coverage for relocated app context update functionality.

The removal of the UpdateAppContext test from this file aligns with the PR objective of moving the app context update functionality to the orchestrator. However, we should ensure equivalent test coverage exists in the orchestrator package.

#!/bin/bash
# Search for new test coverage in orchestrator package
fd -e go -x rg -l "TestUpdateAppContext|TestAppContextUpdate" {} \; orchestrator/

18-18: Verify thorchain TSS dependency management.

The addition of the thorchain TSS blame package import suggests a dependency on an external TSS implementation. Ensure this dependency is properly vendored and version-locked in the module management system.

✅ Verification successful

TSS dependency is properly managed via go.mod replacement directive

The thorchain TSS dependency is correctly declared and managed:

  • Declared version: gitlab.com/thorchain/tss/go-tss v1.6.5
  • Replaced with fork: github.com/zeta-chain/go-tss v0.0.0-20241031223543-18765295f992

The import in zetaclient/zetacore/tx_test.go is consistent with the project's TSS implementation, which is extensively used across the codebase for TSS-related functionality and testing.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the TSS dependency is properly declared in go.mod
rg -A 1 "gitlab.com/thorchain/tss/go-tss" go.mod

Length of output: 86


Script:

#!/bin/bash
# Let's verify the TSS dependency usage and declaration comprehensively

# Check for TSS imports across the codebase
echo "=== TSS Import Usage ==="
rg -l "gitlab.com/thorchain/tss/go-tss"

# Check go.mod content for any thorchain dependencies
echo -e "\n=== Thorchain Dependencies in go.mod ==="
rg "thorchain" go.mod

# Check if there are any vendored TSS packages
echo -e "\n=== Vendored TSS Packages ==="
fd -t d "tss" vendor/

# Look for TSS-related test functions
echo -e "\n=== TSS Test Functions ==="
rg "func.*Test.*TSS|func.*Test.*Blame" -g "*.go"

Length of output: 4450

cmd/zetaclientd/start.go (3)

103-105: LGTM: Successfully decoupled context update logic

The changes effectively move the context update responsibility from the ZetaCore client to dedicated functions, improving separation of concerns and maintainability.

Also applies to: 144-146


349-349: LGTM: Enhanced error handling

The addition of error wrapping with contextual messages improves error traceability and debugging capabilities.

Also applies to: 366-366, 371-371


388-393: LGTM: Clean shutdown handling

The shutdown logic is now more straightforward and properly orchestrated through the maestro.Stop() call.

zetaclient/testutils/mocks/zetacore_client.go (4)

23-24: LGTM: Import addition is appropriate.

The addition of the upgradetypes import from cosmos-sdk is necessary to support the new GetUpgradePlan functionality.


51-79: LGTM: New mock methods follow established patterns.

The newly added mock methods (GetAdditionalChains, GetChainParams, GetSupportedChains, GetUpgradePlan) are well-implemented with:

  • Consistent error handling
  • Proper return value checking
  • Clear panic messages
  • Appropriate type assertions

Also applies to: 197-225, 499-527, 587-613


Line range hint 1-1000: LGTM: Mock implementation maintains consistency and quality.

The mock implementation:

  • Follows consistent patterns across all methods
  • Maintains proper error handling
  • Aligns with the PR objectives of transforming the zetacore client
  • Uses appropriate type assertions and panic messages

Line range hint 1-1: Verify complete removal of Stop-related functionality.

The removal of OnBeforeStop and Stop methods aligns with the PR objective to transform the zetacore client into a stateless client. Let's verify no lingering references exist.

✅ Verification successful

Let me verify if these Stop methods are related to the zetacore client context by checking their usage.


Stop method removal verification completed successfully

The Stop methods found in the codebase are not related to the removed ZetaCore client functionality. They belong to different components:

  • DynamicTicker, Metrics, and TelemetryServer: Infrastructure components
  • Observer and Orchestrator: Higher-level components that use the ZetaCore client
  • Various mocks and utilities

The original OnBeforeStop and Stop methods from the ZetaCore client have been completely removed, with no lingering references, which aligns with the transformation to a stateless client architecture.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the removed methods
# Test: Search for OnBeforeStop and Stop method references. Expect: No results.

echo "Checking for OnBeforeStop references..."
rg "OnBeforeStop" --type go

echo "Checking for Stop method references in zetacore client..."
rg "func.*Stop\(\s*\)" --type go

Length of output: 968


Script:

#!/bin/bash
# Check for zetacore client related Stop references
echo "Checking ZetaCore client interface definition..."
rg "type ZetaCoreClient interface" -A 20 --type go

echo "Checking for imports of zetacore client in files with Stop methods..."
for file in $(rg -l 'func.*Stop\(\s*\)' --type go); do
  echo "=== $file ==="
  rg "zetacore|ZetaCore" "$file"
done

Length of output: 3833

zetaclient/orchestrator/orchestrator.go (2)

137-137: LGTM: Background worker initialization is consistent

The addition of runAppContextUpdater follows the established pattern for background worker initialization and maintains consistent error handling.


780-786: LGTM: Graceful shutdown enhancement

The addition of ticker.WithStopChan(oc.stop) improves the graceful shutdown capabilities of the observer-signer synchronization process.

Let's verify that all ticker usages in the codebase consistently handle graceful shutdown:

✅ Verification successful

All ticker.Run calls consistently implement graceful shutdown

The codebase demonstrates consistent usage of ticker.WithStopChan across all ticker.Run implementations, including:

  • EVM chain observers
  • TON chain observers
  • Orchestrator components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of WithStopChan across ticker implementations
# Expect: All ticker.Run calls should include WithStopChan for graceful shutdown

ast-grep --pattern 'ticker.Run($$$, $$$, $$$, $$$)'

Length of output: 3404

changelog.md (1)

Line range hint 1-1000: Version numbering follows semantic versioning.

The changelog correctly follows semantic versioning (MAJOR.MINOR.PATCH) with 'v' prefix, making version tracking clear and consistent.

zetaclient/orchestrator/contextupdater.go (1)

108-126: Confirm exclusion of ZetaChain from chainParams

The code intentionally excludes ZetaChain from chainParams. Verify that this exclusion is appropriate and that ZetaChain parameters are handled elsewhere to prevent potential issues.

Please confirm that ZetaChain's parameters are managed correctly outside this loop and that excluding it here does not lead to incomplete application context updates.

cmd/zetaclientd/utils.go Outdated Show resolved Hide resolved
zetaclient/zetacore/client.go Show resolved Hide resolved
zetaclient/orchestrator/contextupdater.go Show resolved Hide resolved
Copy link

codecov bot commented Nov 8, 2024

Codecov Report

Attention: Patch coverage is 32.39437% with 96 lines in your changes missing coverage. Please review.

Project coverage is 63.14%. Comparing base (f8df512) to head (c487ace).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
zetaclient/orchestrator/contextupdater.go 41.28% 54 Missing and 10 partials ⚠️
zetaclient/tss/generate.go 0.00% 17 Missing ⚠️
zetaclient/orchestrator/orchestrator.go 0.00% 10 Missing ⚠️
zetaclient/tss/tss_signer.go 0.00% 5 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #3131      +/-   ##
===========================================
+ Coverage    63.08%   63.14%   +0.05%     
===========================================
  Files          423      423              
  Lines        29875    29874       -1     
===========================================
+ Hits         18848    18864      +16     
+ Misses       10186    10170      -16     
+ Partials       841      840       -1     
Files with missing lines Coverage Δ
pkg/rpc/clients.go 68.57% <ø> (ø)
pkg/rpc/clients_cosmos.go 62.50% <ø> (ø)
zetaclient/zetacore/client.go 66.02% <100.00%> (+13.22%) ⬆️
zetaclient/tss/tss_signer.go 21.51% <0.00%> (+0.09%) ⬆️
zetaclient/orchestrator/orchestrator.go 18.48% <0.00%> (-0.08%) ⬇️
zetaclient/tss/generate.go 0.00% <0.00%> (ø)
zetaclient/orchestrator/contextupdater.go 41.28% <41.28%> (ø)

cmd/zetaclientd/start.go Show resolved Hide resolved
cmd/zetaclientd/utils.go Outdated Show resolved Hide resolved
zetaclient/orchestrator/contextupdater.go Outdated Show resolved Hide resolved
Copy link
Contributor

@fbac fbac left a comment

Choose a reason for hiding this comment

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

LGTM

@swift1337 swift1337 added this pull request to the merge queue Nov 12, 2024
Merged via the queue into develop with commit 47b0323 Nov 12, 2024
40 of 41 checks passed
@swift1337 swift1337 deleted the refactor/zetacore-worker branch November 12, 2024 14:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking:cli UPGRADE_LIGHT_TESTS Run make start-upgrade-test-light
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Move worker/async logic out of zetaclient/zetacore
3 participants