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 bootstrap #481

Merged
merged 22 commits into from
Aug 29, 2024
Merged

Refactor bootstrap #481

merged 22 commits into from
Aug 29, 2024

Conversation

sideninja
Copy link
Contributor

@sideninja sideninja commented Aug 27, 2024

Description

Refactor bootstrap procedure to be more modularized. This will allow for better integration testing environment.


For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • New Features

    • Enhanced logging context for improved traceability.
    • Introduced new types for better organization of storage and publishing processes in the EVM gateway.
  • Improvements

    • Refactored control flow to improve application responsiveness and concurrency handling.
    • Enhanced documentation for better clarity on the functionality of key components.
  • Bug Fixes

    • Improved error handling in various setup functions to ensure proper logging and propagation.
  • Tests

    • Updated tests to utilize readiness signals, enhancing reliability and synchronization during test execution.

@sideninja sideninja self-assigned this Aug 27, 2024
Copy link
Contributor

coderabbitai bot commented Aug 27, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes encompass a significant refactoring of the HTTP server implementation, the introduction of new types and methods in the bootstrap process, a restructuring of the main function for improved concurrency, and enhanced documentation across various components. These modifications improve code clarity, organization, and reliability without altering the fundamental logic or functionality of the application.

Changes

Files Change Summary
api/server.go Renamed httpServer to Server, updated constructor and methods accordingly to enhance semantic clarity and maintain functionality.
bootstrap/bootstrap.go Introduced Storages and Publishers types for better organization, refactored the Start function into a New constructor, and modularized setup logic for improved clarity.
cmd/main/main.go Modified the main function to run bootstrap and OS signal handling concurrently, improving application responsiveness.
services/ingestion/engine.go Added detailed documentation for the Engine struct, clarifying its role in event ingestion.
services/traces/engine.go Enhanced documentation for the Engine struct and the NewTracesIngestionEngine function to provide better context.
tests/helpers.go Changed bootstrap initiation from Start to Run with a completion signal, improving test reliability.
tests/integration_test.go Updated test functions to signal readiness using Run instead of Start, enhancing synchronization and consistency in test outcomes.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant Bootstrap
    participant OS_Signal

    Main->>Bootstrap: Run()
    Bootstrap-->>Main: Ready Signal
    Main->>OS_Signal: Wait for signal
    OS_Signal->>Main: Shutdown signal received
    Main->>Bootstrap: Stop()
Loading

🐇✨
In the code, we hop with glee,
Refactoring makes us jump with glee!
New names and types, all neat and bright,
Our logic shines, oh what a sight!
With every change, we dig and burrow,
A clearer path, no room for sorrow! 🌟


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

@@ -35,7 +35,7 @@ type rpcHandler struct {
server *rpc.Server
}

type httpServer struct {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

just renamed to server, because it's not HTTP only since it allows websockets and also the package is API so it makes it api.Server which makes more sense.

@sideninja sideninja marked this pull request as ready for review August 28, 2024 12:22
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 f12df5f and 7bf2b37.

Files selected for processing (7)
  • api/server.go (11 hunks)
  • bootstrap/bootstrap.go (5 hunks)
  • cmd/main/main.go (1 hunks)
  • services/ingestion/engine.go (1 hunks)
  • services/traces/engine.go (2 hunks)
  • tests/helpers.go (1 hunks)
  • tests/integration_test.go (2 hunks)
Files skipped from review due to trivial changes (2)
  • services/ingestion/engine.go
  • services/traces/engine.go
Additional comments not posted (20)
cmd/main/main.go (1)

28-35: Well-implemented OS signal handling.

The goroutine for handling OS signals is correctly set up to listen for SIGINT and SIGTERM and perform cleanup by calling cancel(). This is a good practice for graceful shutdown in Go applications.

api/server.go (13)

38-38: Struct definition is clear and well-organized.

The Server struct is appropriately defined with relevant fields for managing different server functionalities and protocols. This change enhances the clarity and modularity of the server implementation.


66-79: Constructor method is robust and enhances logging.

The NewServer method correctly initializes the Server struct with sensible defaults and enhanced logging through the addition of a component tag. This improvement aids in better log traceability and debugging.


89-89: Proper handling of server address configuration.

The SetListenAddr method correctly checks if the server is already running before attempting to set a new address, preventing potential conflicts or errors. This method is well-implemented with clear error handling.


101-101: Correct retrieval of listening address.

The ListenAddr method appropriately returns the server's listening address based on its current state, providing reliable information whether the server is running or not.


110-110: Robust setup of JSON-RPC over HTTP.

The EnableRPC method effectively checks if JSON-RPC is already enabled and proceeds to set up the server and handler correctly. It handles API registration and potential errors adequately, ensuring a reliable RPC setup.


135-135: Accurate check for JSON-RPC availability.

The rpcAllowed method correctly determines if JSON-RPC over HTTP is enabled by checking the presence of the HTTP handler. This method is implemented clearly and efficiently.


140-140: Effective setup of JSON-RPC over WebSocket.

The EnableWS method ensures that WebSocket communication is not doubly enabled and sets up the server and handler correctly for WebSocket communication. It handles API registration and potential errors adequately, ensuring a reliable WebSocket setup.


164-164: Accurate check for WebSocket availability.

The wsAllowed method correctly determines if JSON-RPC over WebSocket is enabled by checking the presence of the WebSocket handler. This method is implemented clearly and efficiently.


169-169: Proper disabling of WebSocket communication.

The disableWS method effectively checks if WebSocket is enabled before disabling it, ensuring that resources are cleaned up appropriately. This method is well-implemented with clear error handling.


180-180: Comprehensive handling of server start-up.

The Start method correctly handles various scenarios of server start-up, including checking if the server is already running or not configured. It initializes the server with appropriate timeouts and handles errors effectively during start-up.


231-231: Proper disabling of JSON-RPC over HTTP.

The disableRPC method effectively checks if JSON-RPC over HTTP is enabled before disabling it, ensuring that resources are cleaned up appropriately. This method is well-implemented with clear error handling.


241-241: Effective handling of HTTP requests.

The ServeHTTP method correctly differentiates between WebSocket and regular HTTP requests, serving them appropriately based on the server configuration. This method is well-implemented, ensuring that all types of requests are handled correctly.


291-291: Comprehensive handling of server shutdown.

The Stop method effectively shuts down the server, ensuring that all resources are cleanly released and providing appropriate logging. This method handles the shutdown process thoroughly, including stopping any active handlers.

bootstrap/bootstrap.go (6)

28-35: Well-designed storage encapsulation.

The Storages type effectively groups various storage components, enhancing the organization and modularity of the storage-related logic. This type is well-designed and appropriately encapsulates the necessary components.


37-41: Effective grouping of publishing components.

The Publishers type appropriately groups different publishers for blocks, transactions, and logs, streamlining the publishing process. This type is well-designed and enhances the modularity and organization of the publishing logic.


43-54: Expanded Bootstrap struct enhances modularity.

The expanded Bootstrap struct effectively includes new types Storages and Publishers along with additional fields for better dependency management. This expansion improves the clarity and modularity of the code, making it easier to manage and maintain.


56-81: Constructor-like method New is well-implemented.

The New function effectively acts as a constructor for the Bootstrap struct, handling the setup of storages, publishers, and the cross-spork client comprehensively. It manages dependencies well and provides clear error handling, ensuring a properly configured instance is returned.


Line range hint 84-138: Comprehensive handling of event ingestion.

The StartEventIngestion method, now operating on the Bootstrap struct, effectively handles the event ingestion process. It fetches the latest block, sets up the ingestion engine, and provides clear error handling and logging. This method is well-implemented and ensures a robust event ingestion setup.


140-161: Effective handling of trace downloading.

The StartTraceDownloader method, now operating on the Bootstrap struct, effectively handles the trace downloading process. It

Comment on lines +37 to +46
ready := make(chan struct{})
go func() {
err = bootstrap.Run(ctx, cfg, ready)
if err != nil {
panic(err)
}
}()

<-ready
fmt.Println("EVM gateway bootstrap completed, services running")
Copy link
Contributor

Choose a reason for hiding this comment

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

Effective use of concurrency for the bootstrap process.

The goroutine for running the bootstrap process is well-implemented, using a channel to signal readiness, which synchronizes with the main function. This approach enhances modularity and responsiveness. Ensure that error handling is robust and consider logging the error before panicking to aid in debugging.

Consider adding logging before panicking on bootstrap errors:

- panic(err)
+ logger.Error("Bootstrap failed:", err)
+ panic(err)
Committable suggestion

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

Suggested change
ready := make(chan struct{})
go func() {
err = bootstrap.Run(ctx, cfg, ready)
if err != nil {
panic(err)
}
}()
<-ready
fmt.Println("EVM gateway bootstrap completed, services running")
ready := make(chan struct{})
go func() {
err = bootstrap.Run(ctx, cfg, ready)
if err != nil {
logger.Error("Bootstrap failed:", err)
panic(err)
}
}()
<-ready
fmt.Println("EVM gateway bootstrap completed, services running")

Comment on lines +83 to +89
ready := make(chan struct{})
go func() {
err = bootstrap.Start(ctx, cfg)
err := bootstrap.Run(ctx, cfg, ready)
require.NoError(t, err)
}()
time.Sleep(500 * time.Millisecond) // some time to startup

<-ready
Copy link
Contributor

Choose a reason for hiding this comment

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

Improved test synchronization with bootstrap process.

The modification to use a readiness channel in Test_ConcurrentTransactionSubmission enhances test reliability by ensuring the bootstrap process is fully ready before proceeding. This change helps avoid race conditions. Consider adding error handling for the goroutine running the bootstrap process to enhance test robustness.

Add error handling for the bootstrap process within the test:

- require.NoError(t, err)
+ if err != nil {
+     t.Errorf("Bootstrap failed: %v", err)
+     return
+ }
Committable suggestion

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

Suggested change
ready := make(chan struct{})
go func() {
err = bootstrap.Start(ctx, cfg)
err := bootstrap.Run(ctx, cfg, ready)
require.NoError(t, err)
}()
time.Sleep(500 * time.Millisecond) // some time to startup
<-ready
ready := make(chan struct{})
go func() {
err := bootstrap.Run(ctx, cfg, ready)
if err != nil {
t.Errorf("Bootstrap failed: %v", err)
return
}
}()
<-ready

Comment on lines +221 to +227
ready := make(chan struct{})
go func() {
err = bootstrap.Start(ctx, cfg)
err := bootstrap.Run(ctx, cfg, ready)
require.NoError(t, err)
}()
time.Sleep(2500 * time.Millisecond) // some time to startup

<-ready
Copy link
Contributor

Choose a reason for hiding this comment

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

Consistent improvement in test setup.

The use of a readiness channel in Test_CloudKMSConcurrentTransactionSubmission mirrors the improvements made in the other test function, standardizing the approach and enhancing reliability. Similar to the previous test, consider adding error handling for the bootstrap process to ensure test robustness.

Add error handling for the bootstrap process within the test:

- require.NoError(t, err)
+ if err != nil {
+     t.Errorf("Bootstrap failed: %v", err)
+     return
+ }
Committable suggestion

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

Suggested change
ready := make(chan struct{})
go func() {
err = bootstrap.Start(ctx, cfg)
err := bootstrap.Run(ctx, cfg, ready)
require.NoError(t, err)
}()
time.Sleep(2500 * time.Millisecond) // some time to startup
<-ready
ready := make(chan struct{})
go func() {
err := bootstrap.Run(ctx, cfg, ready)
if err != nil {
t.Errorf("Bootstrap failed: %v", err)
return
}
}()
<-ready

Comment on lines +160 to +167
bootstrapDone := make(chan struct{})
go func() {
err = bootstrap.Start(ctx, cfg)
err = bootstrap.Run(ctx, cfg, bootstrapDone)
require.NoError(t, err)
}()

time.Sleep(2 * time.Second) // some time to startup
<-bootstrapDone

Copy link
Contributor

Choose a reason for hiding this comment

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

Enhanced control flow in test setup.

The introduction of a readiness channel in servicesSetup improves the reliability of tests by ensuring the bootstrap process is fully completed before proceeding. This modification enhances the control flow and reduces potential timing issues. Consider adding error handling for the bootstrap process to ensure robustness.

Add error handling for the bootstrap process within the test setup:

- require.NoError(t, err)
+ if err != nil {
+     logger.Error("Bootstrap failed:", err)
+     return
+ }

Committable suggestion was skipped due to low confidence.

bootstrap/bootstrap.go Outdated Show resolved Hide resolved
bootstrap/bootstrap.go Outdated Show resolved Hide resolved
Copy link
Collaborator

@m-Peter m-Peter left a comment

Choose a reason for hiding this comment

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

Very nice restructure 👏
Left just a couple of comments/questions.

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 UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7bf2b37 and 4c80b63.

Files selected for processing (1)
  • tests/helpers.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/helpers.go

@sideninja sideninja merged commit d2a1b06 into main Aug 29, 2024
2 checks passed
@m-Peter m-Peter deleted the gregor/bootstrat-refactor branch September 5, 2024 09:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants