Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schema/appdata): async listener mux'ing #20879

Merged
merged 17 commits into from
Jul 25, 2024
Merged

Conversation

aaronc
Copy link
Member

@aaronc aaronc commented Jul 4, 2024

Description

This PR is part of the implementation of #20647. It introduces appdata.Listener utilities for:

  • multiplexing listener writes to multiple listeners
  • backgrounding writes to a listener to a separate goroutine
  • multiplexing writes to multiple listeners each processing in their own goroutine

Author Checklist

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

I have...

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

Reviewers Checklist

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

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

I have...

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

Summary by CodeRabbit

  • New Features

    • Introduced asynchronous event handling capabilities for improved performance.
    • Added functionality to manage event listeners in sequence using the new multiplexing listener.
  • Tests

    • Implemented tests to validate asynchronous listener behavior and ensure correct execution order of multiplexed event handling.

Copy link
Contributor

coderabbitai bot commented Jul 4, 2024

Walkthrough

Walkthrough

The recent changes enhance the appdata package by introducing asynchronous event handling capabilities and a multiplexing listener feature. Key additions include the AsyncListenerOptions struct, AsyncListenerMux, and AsyncListener functions for concurrent listener management, along with a new ListenerMux function for directing events to multiple listeners. Corresponding tests have been implemented to validate these functionalities and ensure correct callback execution.

Changes

Files Change Summary
schema/appdata/async.go Introduced AsyncListenerOptions, AsyncListenerMux, and AsyncListener for asynchronous event handling.
schema/appdata/async_test.go Added test functions TestAsyncListenerMux and TestAsyncListener to validate asynchronous listener behavior.
schema/appdata/mux.go Defined ListenerMux to forward events to multiple listeners in a specified order.
schema/appdata/mux_test.go Added test functions to validate ListenerMux behavior and callback order handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AsyncListenerMux
    participant Listener1
    participant Listener2
    
    Client->>AsyncListenerMux: Send Event
    AsyncListenerMux->>Listener1: Forward Event
    AsyncListenerMux->>Listener2: Forward Event
    
    Listener1->>AsyncListenerMux: Acknowledge Event
    Listener2->>AsyncListenerMux: Acknowledge Event
    AsyncListenerMux->>Client: Confirm Event Handling
Loading
sequenceDiagram
    participant Client
    participant AsyncListener
    participant EventProcessor
    
    Client->>AsyncListener: Send Event
    AsyncListener->>EventProcessor: Process Event (goroutine)
    EventProcessor->>AsyncListener: Event Result
    AsyncListener->>Client: Confirm Event Handling
Loading

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

schema/appdata/async.go Fixed Show fixed Hide fixed
@aaronc aaronc marked this pull request as ready for review July 10, 2024 11:14
@aaronc aaronc requested a review from a team as a code owner July 10, 2024 11:14
Copy link
Contributor

@aaronc your pull request is missing a changelog!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

Outside diff range, codebase verification and nitpick comments (3)
schema/appdata/mux.go (3)

3-4: Ensure documentation clarity.

The comments should clarify that the returned listener will forward events to all provided listeners and that callbacks will only be registered if at least one listener has a non-nil callback.

- // ListenerMux returns a listener that forwards received events to all the provided listeners in order.
- // A callback is only registered if a non-nil callback is present in at least one of the listeners.
+ // ListenerMux returns a listener that forwards received events to all the provided listeners in order.
+ // A callback is only registered if a non-nil callback is present in at least one of the listeners.
+ // The returned listener will forward events to all provided listeners.

5-7: Initialize mux with default values.

Ensure that mux is correctly initialized with default values for all possible callback functions to prevent nil pointer dereference.

  • schema/appdata/mux.go, function ListenerMux, initialize mux with default no-op functions for all callbacks.
Analysis chain

Initialize mux with default values.

Ensure that mux is correctly initialized with default values for all possible callback functions to prevent nil pointer dereference.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all callback functions in Listener are initialized with default values.

# Test: Search for the Listener struct definition. Expect: All callback functions are initialized.
rg --type go -A 10 'type Listener struct'

Length of output: 1057


Script:

#!/bin/bash
# Description: Retrieve the complete definition of the Listener struct to identify all callback functions.
rg --type go -A 20 'type Listener struct' schema/appdata/listener.go

Length of output: 1145


Script:

#!/bin/bash
# Description: Check the ListenerMux function implementation to see how mux is initialized.
rg --type go -A 10 'func ListenerMux' schema/appdata/mux.go

Length of output: 433


120-121: Ensure default initialization for all callbacks.

The Listener struct is instantiated without initializing its callback functions in the following locations:

  • schema/appdata/mux.go:
    mux := Listener{}
  • schema/appdata/async.go:
    res := Listener{}

Ensure that all possible callbacks in the returned Listener are initialized with default values to prevent potential nil pointer dereferences.

Analysis chain

Ensure default initialization for all callbacks.

Ensure that all possible callbacks in the returned listener are initialized with default values.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all callbacks in the returned Listener are initialized with default values.

# Test: Search for the Listener struct definition. Expect: All callback functions are initialized.
rg --type go -A 10 'type Listener struct'

Length of output: 1057


Script:

#!/bin/bash
# Description: Extract the complete definition of the Listener struct to verify initialization of all callback functions.

# Search for the complete definition of the Listener struct.
rg --type go -A 30 'type Listener struct' schema/appdata/listener.go

Length of output: 1804


Script:

#!/bin/bash
# Description: Search for instances where the Listener struct is instantiated and verify initialization of callbacks.

# Find instances of Listener struct instantiation.
rg --type go 'Listener{'

Length of output: 108


Script:

#!/bin/bash
# Description: Search for instances where the Listener struct is instantiated and verify initialization of callbacks.

# Find instances of Listener struct instantiation.
rg --type go 'Listener\{'

Length of output: 1191


Script:

#!/bin/bash
# Description: Extract context around the instantiation of Listener to verify initialization of callbacks.

# Extract context around the instantiation in mux.go
rg --type go -A 10 -B 10 'Listener\{\}' schema/appdata/mux.go

# Extract context around the instantiation in async.go
rg --type go -A 10 -B 10 'Listener\{\}' schema/appdata/async.go

Length of output: 1904

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ab6400f and 3d5ab58.

Files selected for processing (4)
  • schema/appdata/async.go (1 hunks)
  • schema/appdata/async_test.go (1 hunks)
  • schema/appdata/mux.go (1 hunks)
  • schema/appdata/mux_test.go (1 hunks)
Additional context used
Path-based instructions (4)
schema/appdata/mux.go (1)

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

schema/appdata/mux_test.go (2)

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


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

schema/appdata/async_test.go (2)

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


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

schema/appdata/async.go (1)

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

Additional comments not posted (12)
schema/appdata/mux_test.go (5)

8-33: Ensure comprehensive test coverage.

The "empty" sub-test verifies that the returned listener has nil callbacks when no listeners are provided. This is a good basic test, but consider adding more edge cases.


35-61: Ensure test order reflects realistic usage.

The "all called once" sub-test verifies that all callbacks are called in order. This test is thorough and covers realistic usage scenarios.


64-86: Ensure comprehensive callback testing.

The callAllCallbacksOnces function ensures that all callbacks are called once. This is a good utility function for testing.


88-119: Ensure accurate callback simulation.

The callCollector function simulates callbacks and collects call information. This is a useful utility for testing.


121-131: Ensure accurate call order verification.

The checkExpectedCallOrder function verifies the order of callback invocations. This is a crucial utility for ensuring the correctness of callback ordering.

schema/appdata/async_test.go (5)

10-34: Ensure comprehensive test coverage.

The "empty" sub-test verifies that the returned listener has nil callbacks when no listeners are provided. This is a good basic test, but consider adding more edge cases.


36-68: Ensure context cancellation is handled correctly.

The "call cancel" sub-test verifies that all callbacks are called and the context is cancelled correctly. This test is thorough and covers realistic usage scenarios.


70-87: Ensure error handling in commit is tested.

The "error on commit" sub-test verifies error handling during commit. This is a crucial test for ensuring robustness.


90-124: Ensure context cancellation is handled correctly.

The "call cancel" sub-test verifies that all callbacks are called and the context is cancelled correctly. This test is thorough and covers realistic usage scenarios.


126-147: Ensure error handling in callbacks is tested.

The "error" sub-test verifies error handling during callback execution. This is a crucial test for ensuring robustness.

schema/appdata/async.go (2)

8-19: Ensure comprehensive documentation for struct fields.

The AsyncListenerOptions struct defines options for async listeners and listener mux's. The documentation should ensure that all fields are clearly explained.


22-55: Ensure proper handling of asynchronous listeners.

The AsyncListenerMux function manages asynchronous listeners and ensures that all commit errors are handled correctly. This implementation is crucial for maintaining robustness in concurrent contexts.

schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/mux.go Outdated Show resolved Hide resolved
schema/appdata/async.go Dismissed Show dismissed Hide dismissed
schema/appdata/mux.go Outdated Show resolved Hide resolved
packetChan <- data
return nil
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

res.callbacks := make(func(data Packet) error, 0)

How about having a general callback slice instead of all individual callbacks?

Copy link
Member Author

@aaronc aaronc Jul 25, 2024

Choose a reason for hiding this comment

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

I'm not sure I follow how this would work. Could you explain more?

Copy link
Contributor

@cool-develope cool-develope Jul 25, 2024

Choose a reason for hiding this comment

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

IMO, we can keep only one callback function within Listener, since all callbacks StartBlock, OnTx ... are in the same format as func(packet Packet) error. And then within the callback implementation, we can deal with different packet type like ModuleInitializationData, StartBlockData, and so on using a switch statement. It will reduce the duplicated imp here, and in mux.go

Copy link
Contributor

Choose a reason for hiding this comment

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

We already defined the different packet data structures, so we don't need to distinguish the callback functions.

Copy link
Member Author

@aaronc aaronc Jul 25, 2024

Choose a reason for hiding this comment

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

The purpose of distinguishing the different callback functions is to signal what each listener is subscribing to. If listeners don't listen to events at all, then OnEvent should be nil and then the producers won't send any events. If there's only one callback function then a producer has to always send all packets even if the consumers are only interested in certain packet types. In the async case it simplifies what is sent over each packet channel to only the subscription callbacks that are non nil.

Copy link
Contributor

Choose a reason for hiding this comment

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

that makes sense!

aaronc and others added 2 commits July 25, 2024 14:05
Co-authored-by: cool-developer <51834436+cool-develope@users.noreply.github.com>
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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3d5ab58 and 6b6eb20.

Files selected for processing (1)
  • schema/appdata/mux.go (1 hunks)
Additional context used
Path-based instructions (1)
schema/appdata/mux.go (1)

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

Additional comments not posted (8)
schema/appdata/mux.go (8)

1-23: LGTM! Initialization and InitializeModuleData handling are correct.

The initialization of the Listener struct and the handling of InitializeModuleData callbacks are well-implemented.


25-40: LGTM! StartBlock handling is correct.

The handling of StartBlock callbacks is well-implemented.


42-57: LGTM! OnTx handling is correct.

The handling of OnTx callbacks is well-implemented.


59-74: LGTM! OnEvent handling is correct.

The handling of OnEvent callbacks is well-implemented.


76-91: LGTM! OnKVPair handling is correct.

The handling of OnKVPair callbacks is well-implemented.


93-108: LGTM! OnObjectUpdate handling is correct.

The handling of OnObjectUpdate callbacks is well-implemented.


110-125: LGTM! Commit handling is correct.

The handling of Commit callbacks is well-implemented.


127-128: LGTM! Return statement is correct.

The return statement correctly returns the initialized Listener struct.

@aaronc aaronc added this pull request to the merge queue Jul 25, 2024
Merged via the queue into main with commit 683371f Jul 25, 2024
76 checks passed
@aaronc aaronc deleted the aaronc/schema-appdata-utils branch July 25, 2024 13:57
alpe added a commit that referenced this pull request Jul 26, 2024
* main:
  feat(log): remove core dependency and update core interface to be dependency free (#21045)
  chore: fix some comments (#21085)
  feat: simulate nested messages (#20291)
  chore(network): remove `DefaultConfigWithAppConfigWithQueryGasLimit` (#21055)
  fix(runtime): remove `appv1alpha1.Config` from runtime (#21042)
  feat(simapp/v2): Add store server to testnet init cmd (#21076)
  chore(indexer/postgres): update to changes on main (#21077)
  feat(schema/appdata): async listener mux'ing (#20879)
  ci: Use large box for 052 branch sims on CI (#21067)
  chore(all): replace all `fmt.Errorf` without paramters with `errors.New` (#21068)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants