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

Move FinalizeBlock event staging logic into a generic EventStager #2435

Merged
merged 2 commits into from
Oct 2, 2024

Conversation

teddyding
Copy link
Contributor

@teddyding teddyding commented Oct 2, 2024

Changelist

Create a new EventStager struct that manages the staging and retrieval of FinalizeBlock event, so that it can be used by all modules.

Test Plan

Tested FNS via localnet.

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced a new EventStager for efficient staging and retrieval of events during the FinalizeBlock process.
    • Enhanced event management in the FullNodeStreamingManager with a new dependency on the finalizeblock package.
  • Bug Fixes

    • Removed unused and non-functional methods related to finalized subaccount updates, streamlining the code.
  • Documentation

    • Updated interface definitions to reflect the removal of the SendFinalizedSubaccountUpdates method across various components.

Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

The changes introduce a new EventStager type to manage event staging and retrieval during the FinalizeBlock process in a blockchain context. This type is utilized within the FullNodeStreamingManagerImpl, which has been updated to rely on the EventStager for staging events. Several methods related to subaccount updates and event staging have been removed or modified across various files, streamlining the event handling process. The SendFinalizedSubaccountUpdates method has been eliminated from multiple interfaces and implementations, indicating a shift in how subaccount updates are processed.

Changes

File Change Summary
protocol/finalizeblock/event_stager.go Added EventStager type, constructor NewEventStager, and methods for staging and retrieving events.
protocol/streaming/full_node_streaming_manager.go Added dependency on finalizeblock, removed stageFinalizeBlockEvent, updated methods to use finalizeBlockStager.
protocol/streaming/noop_streaming_manager.go Removed SendFinalizedSubaccountUpdates method.
protocol/streaming/types/interface.go Removed SendFinalizedSubaccountUpdates method from FullNodeStreamingManager interface.
protocol/x/clob/types/expected_keepers.go Removed SendFinalizedSubaccountUpdates method from SubaccountsKeeper interface.
protocol/x/subaccounts/keeper/subaccount.go Removed SendFinalizedSubaccountUpdates method, minor adjustments in GetFullNodeStreamingManager.
protocol/x/subaccounts/types/types.go Removed SendFinalizedSubaccountUpdates method from SubaccountsKeeper interface.

Possibly related PRs

Suggested labels

indexer, proto

Suggested reviewers

  • jayy04
  • dydxwill

Poem

In the burrow where events do play,
A stager hops to save the day.
With blocks aligned and updates neat,
Our code now dances to a new beat!
So let us cheer, with thumps and twirls,
For streamlined paths in our rabbit world! 🐇✨


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.

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.

@teddyding teddyding marked this pull request as ready for review October 2, 2024 18:40
@teddyding teddyding requested a review from a team as a code owner October 2, 2024 18:40
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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e2438dd and 01d9cc2.

📒 Files selected for processing (7)
  • protocol/finalizeblock/event_stager.go (1 hunks)
  • protocol/streaming/full_node_streaming_manager.go (6 hunks)
  • protocol/streaming/noop_streaming_manager.go (0 hunks)
  • protocol/streaming/types/interface.go (0 hunks)
  • protocol/x/clob/types/expected_keepers.go (0 hunks)
  • protocol/x/subaccounts/keeper/subaccount.go (0 hunks)
  • protocol/x/subaccounts/types/types.go (0 hunks)
💤 Files with no reviewable changes (5)
  • protocol/streaming/noop_streaming_manager.go
  • protocol/streaming/types/interface.go
  • protocol/x/clob/types/expected_keepers.go
  • protocol/x/subaccounts/keeper/subaccount.go
  • protocol/x/subaccounts/types/types.go
🔇 Additional comments (6)
protocol/streaming/full_node_streaming_manager.go (6)

23-24: Addition of the finalizeblock import is appropriate

The new import of the finalizeblock package is necessary for managing finalize block events. This addition is appropriate and correctly placed.


66-66: Introduction of finalizeBlockStager field

Adding the finalizeBlockStager field to the FullNodeStreamingManagerImpl struct enhances the management of finalize block events. This integration is appropriate and aligns with the objectives of the PR.


124-129: Correct initialization of finalizeBlockStager

The finalizeBlockStager is properly initialized using finalizeblock.NewEventStager. The parameters provided ensure that it functions as intended.


408-408: Staging subaccount update events

The use of sm.finalizeBlockStager.StageFinalizeBlockEvent correctly stages subaccount update events for processing after block finalization.


558-558: Staging orderbook update events

The call to sm.finalizeBlockStager.StageFinalizeBlockEvent appropriately stages orderbook updates for post-finalization processing.


633-633: Staging order fill events

Using sm.finalizeBlockStager.StageFinalizeBlockEvent to stage order fill events aligns with the new event staging logic and is correctly implemented.

protocol/finalizeblock/event_stager.go Outdated Show resolved Hide resolved
protocol/finalizeblock/event_stager.go Show resolved Hide resolved
protocol/finalizeblock/event_stager.go Show resolved Hide resolved
protocol/streaming/full_node_streaming_manager.go Outdated Show resolved Hide resolved
@@ -710,32 +691,6 @@ func getStreamUpdatesForSubaccountUpdates(
return streamUpdates, subaccountIds
}

// SendFinalizedSubaccountUpdates groups subaccount updates by their subaccount ids and
// sends messages to the subscribers.
func (sm *FullNodeStreamingManagerImpl) SendFinalizedSubaccountUpdates(
Copy link
Contributor Author

@teddyding teddyding Oct 2, 2024

Choose a reason for hiding this comment

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

This method and below interface are unused and should've been deleted (as part of internalize PR)

Comment on lines 408 to 411
sm.finalizeBlockStager.StageFinalizeBlockEvent(
ctx,
sm.cdc.MustMarshal(&stagedEvent),
)
Copy link
Contributor

Choose a reason for hiding this comment

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

meganit: the Getter returns []T so let's also pass in T instead of []byte for consistency


// GetStagedFinalizeBlockEventsFromStore retrieves all staged events from the store.
func (s EventStager[T]) GetStagedFinalizeBlockEventsFromStore(
store storetypes.KVStore,
Copy link
Contributor

Choose a reason for hiding this comment

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

also meganit: take in ctx and move the free gas meter here for consistency w setter method

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

🧹 Outside diff range and nitpick comments (6)
protocol/finalizeblock/event_stager.go (2)

15-21: LGTM: EventStager struct is well-designed.

The use of generics with the proto.Message constraint is a good choice for type-safe event handling. The struct fields provide all necessary components for event staging and retrieval.

Consider adding a brief comment for each field to explain their purpose, which would enhance the struct's documentation.


23-36: LGTM: NewEventStager constructor is well-implemented.

The constructor correctly initializes all fields of the EventStager struct.

Consider adding validation for input parameters, especially for transientStoreKey and cdc, to ensure they are not nil. This would prevent potential runtime panics. For example:

func NewEventStager[T proto.Message](
	transientStoreKey storetypes.StoreKey,
	cdc codec.BinaryCodec,
	stagedEventCountKey string,
	stagedEventKeyPrefix string,
) EventStager[T] {
	if transientStoreKey == nil {
		panic("transientStoreKey cannot be nil")
	}
	if cdc == nil {
		panic("cdc cannot be nil")
	}
	return EventStager[T]{
		transientStoreKey:    transientStoreKey,
		cdc:                  cdc,
		stagedEventCountKey:  stagedEventCountKey,
		stagedEventKeyPrefix: stagedEventKeyPrefix,
	}
}
protocol/streaming/full_node_streaming_manager.go (4)

124-129: LGTM: Proper initialization of finalizeBlockStager

The initialization of finalizeBlockStager in the NewFullNodeStreamingManager function is correct and ensures that the EventStager is ready for use. This aligns well with the PR's objective of implementing a generic EventStager for FinalizeBlock events.

Consider extracting the NewEventStager parameters into named constants at the package level for improved readability and maintainability. For example:

const (
    StagedEventsCountKey   = "StagedEventsCount"
    StagedEventsKeyPrefix  = "StagedEvents/"
)

Then use these constants in the NewEventStager call.


408-411: LGTM: Proper use of finalizeBlockStager for subaccount updates

The modification to use finalizeBlockStager.StageFinalizeBlockEvent for staging subaccount updates is correct and aligns with the new generic EventStager approach. The DeliverTx mode check ensures that only finalized updates are staged.

Consider adding error handling for the StageFinalizeBlockEvent call. While it may not return an error in the current implementation, it's a good practice to handle potential future changes. For example:

if err := sm.finalizeBlockStager.StageFinalizeBlockEvent(ctx, &stagedEvent); err != nil {
    sm.logger.Error("Failed to stage finalize block event", "error", err)
    // Decide if you want to return the error or handle it differently
}

556-559: LGTM: Consistent use of finalizeBlockStager for orderbook updates

The modification to use finalizeBlockStager.StageFinalizeBlockEvent for staging orderbook updates is correct and consistent with the changes made in other methods. The DeliverTx mode check ensures that only finalized updates are staged.

For consistency with the suggested improvement in the SendSubaccountUpdate method, consider adding error handling here as well:

if err := sm.finalizeBlockStager.StageFinalizeBlockEvent(ctx, &stagedEvent); err != nil {
    sm.logger.Error("Failed to stage finalize block event for orderbook update", "error", err)
    // Decide if you want to return the error or handle it differently
}

This maintains consistency across similar operations and improves error handling throughout the codebase.


631-634: LGTM: Consistent use of finalizeBlockStager for orderbook fill updates

The modification to use finalizeBlockStager.StageFinalizeBlockEvent for staging orderbook fill updates is correct and consistent with the changes made in other methods. The DeliverTx mode check ensures that only finalized updates are staged.

For consistency with the suggested improvements in other methods, consider adding error handling here as well:

if err := sm.finalizeBlockStager.StageFinalizeBlockEvent(ctx, &stagedEvent); err != nil {
    sm.logger.Error("Failed to stage finalize block event for orderbook fill update", "error", err)
    // Decide if you want to return the error or handle it differently
}

This maintains consistency across similar operations and improves error handling throughout the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 01d9cc2 and ff9eb5f.

📒 Files selected for processing (2)
  • protocol/finalizeblock/event_stager.go (1 hunks)
  • protocol/streaming/full_node_streaming_manager.go (6 hunks)
🔇 Additional comments (6)
protocol/finalizeblock/event_stager.go (3)

1-13: LGTM: Package declaration and imports are appropriate.

The package name finalizeblock and the imported packages align well with the file's purpose of managing events during the FinalizeBlock process.


38-56: ⚠️ Potential issue

Consider improving error handling and gas usage in GetStagedFinalizeBlockEvents.

While the method effectively retrieves staged events, there are a few areas for improvement:

  1. The use of an infinite gas meter (NewFreeInfiniteGasMeter()) bypasses gas consumption checks. This could potentially lead to security vulnerabilities or unintended behaviors in gas accounting.

  2. The use of MustUnmarshal can cause panics if the data is invalid or corrupted. This could lead to stability issues in production.

To address these concerns:

  1. Consider using a regular context with gas metering, or document why infinite gas is necessary here.

  2. Replace MustUnmarshal with regular Unmarshal and handle potential errors gracefully. For example:

if err := s.cdc.Unmarshal(bytes, event); err != nil {
    // Handle the error appropriately, such as logging or returning it
    // For example:
    return nil, fmt.Errorf("failed to unmarshal event: %w", err)
}

These changes will improve the robustness and safety of the code.


1-83: Overall assessment: Good implementation with room for improvement.

The EventStager provides a solid foundation for managing events during the FinalizeBlock process. The use of generics and the overall structure are commendable. However, there are several areas where the code could be improved:

  1. Error handling: Replace MustUnmarshal and MustMarshal with their non-panicking counterparts and handle errors explicitly.
  2. Gas usage: Reconsider the use of infinite gas meters or provide clear documentation justifying their necessity.
  3. Input validation: Add checks for nil inputs in the constructor and methods.
  4. Documentation: Enhance inline comments, especially for struct fields.

Addressing these points will significantly improve the robustness and maintainability of the code.

To ensure that the EventStager is being used correctly throughout the codebase, please run the following verification script:

This script will help identify any potential misuse or inconsistencies in how the EventStager is being utilized across the project.

protocol/streaming/full_node_streaming_manager.go (3)

23-24: LGTM: New import and struct field align with PR objectives

The addition of the finalizeblock package import and the new finalizeBlockStager field in the FullNodeStreamingManagerImpl struct are well-aligned with the PR's objective of creating a generic EventStager. This change should enhance the modularity and reusability of the event handling logic across all modules.

Also applies to: 65-66


Line range hint 1-1000: Overall LGTM: Successful implementation of generic EventStager

The changes in this file successfully implement the generic EventStager for managing FinalizeBlock events across multiple methods. This aligns well with the PR objectives of enhancing modularity and reusability of event handling logic.

Key improvements:

  1. Consistent use of finalizeBlockStager for staging events in DeliverTx mode.
  2. Proper initialization of the EventStager in the constructor.
  3. Consistent checks for DeliverTx mode before staging events.

Suggestions for further improvement:

  1. Implement consistent error handling across all methods using the EventStager.
  2. Consider extracting some constants for improved readability.
  3. Replace the panic in GetStagedFinalizeBlockEvents with more graceful error handling.

These changes significantly enhance the structure and maintainability of the event handling system in the FullNodeStreamingManager.


418-431: ⚠️ Potential issue

Avoid using panic; handle nil events gracefully

While the use of finalizeBlockStager.GetStagedFinalizeBlockEvents is correct, the panic on encountering a nil event could lead to application instability. It's better to handle this scenario more gracefully to maintain application robustness.

Consider modifying the code to log the error and continue processing:

 results := make([]clobtypes.StagedFinalizeBlockEvent, len(events))
 for i, event := range events {
 	if event == nil {
-		panic("Got nil event from finalizeBlockStager")
+		sm.logger.Error("Received nil event from finalizeBlockStager", "index", i)
+		continue
 	}
 	results[i] = *event
 }
 return results

This approach logs the error and skips the nil event, allowing the function to return the successfully retrieved events without crashing the application.

Comment on lines +68 to +83
// StageFinalizeBlockEvent stages an event in the transient store.
func (s EventStager[T]) StageFinalizeBlockEvent(
ctx sdk.Context,
stagedEvent T,
) {
noGasCtx := ctx.WithGasMeter(ante_types.NewFreeInfiniteGasMeter())
store := noGasCtx.TransientStore(s.transientStoreKey)

// Increment events count.
count := s.getStagedEventsCount(store)
store.Set([]byte(s.stagedEventCountKey), lib.Uint32ToKey(count+1))

// Store events keyed by index.
store = prefix.NewStore(store, []byte(s.stagedEventKeyPrefix))
store.Set(lib.Uint32ToKey(count), s.cdc.MustMarshal(stagedEvent))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling and consider gas usage in StageFinalizeBlockEvent.

The method effectively stages events, but there are areas for improvement:

  1. The use of an infinite gas meter (NewFreeInfiniteGasMeter()) bypasses gas consumption checks. This could potentially lead to security vulnerabilities or unintended behaviors in gas accounting.

  2. The use of MustMarshal can cause panics if marshaling fails. This could lead to stability issues in production.

  3. There's no validation of the input event.

To address these concerns:

  1. Consider using a regular context with gas metering, or document why infinite gas is necessary here.

  2. Replace MustMarshal with regular Marshal and handle potential errors gracefully. For example:

bytes, err := s.cdc.Marshal(stagedEvent)
if err != nil {
    // Handle the error appropriately, such as logging or returning it
    return fmt.Errorf("failed to marshal event: %w", err)
}
store.Set(lib.Uint32ToKey(count), bytes)
  1. Add validation for the input event to ensure it's not nil:
if stagedEvent == nil {
    return fmt.Errorf("staged event cannot be nil")
}

These changes will improve the robustness and safety of the code.

@teddyding
Copy link
Contributor Author

@Mergifyio backport release/protocol/v7.x

Copy link
Contributor

mergify bot commented Oct 2, 2024

backport release/protocol/v7.x

✅ Backports have been created

@teddyding teddyding merged commit 53b298b into main Oct 2, 2024
21 checks passed
@teddyding teddyding deleted the td/event-stager branch October 2, 2024 19:42
mergify bot pushed a commit that referenced this pull request Oct 2, 2024
teddyding added a commit that referenced this pull request Oct 2, 2024
@coderabbitai coderabbitai bot mentioned this pull request Oct 2, 2024
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants