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

A bunch of improvements #479

Merged
merged 2 commits into from
Feb 12, 2025
Merged

A bunch of improvements #479

merged 2 commits into from
Feb 12, 2025

Conversation

mkysel
Copy link
Collaborator

@mkysel mkysel commented Feb 11, 2025

Hard to break these apart as they are all kinda entangled.

  1. We know that TestReadOwnWritesGuarantee occasionally fails (Test failure TestReadOwnWritesGuarantee #478) but the output of that test is mangled with the output from the previous test.
    The mangling is caused by unclean shutdown. As those resources get cleaned up, the output gets printed all over the place.
    In tests, we don't need soft shutdown, so this PR introduces a hard shutdown to speed up tests.

  2. The sync worker was leaking connections

  3. Recv() is blocking and does not listen to ctx Done. A separate mechanism has to be introduced to handle shutdowns cleanly. This is the same pattern that we use in nodeCursorTracker

  4. Create DBs with the name of the test in them. Makes SQL debugging easier.

Summary by CodeRabbit

  • New Features
    • Configurable timeout settings now enable a graceful shutdown process to ensure active operations complete reliably.
  • Refactor
    • Enhanced shutdown logic with timeout parameters for improved control over server shutdown processes.
    • Optimized background processing with non-blocking error handling for improved responsiveness.
  • Tests
    • Enhanced testing utilities with refined resource cleanup and dynamic naming to bolster test robustness.

@mkysel mkysel requested a review from a team as a code owner February 11, 2025 20:38
Copy link

coderabbitai bot commented Feb 11, 2025

Walkthrough

The changes introduce timeout parameters into various shutdown methods across multiple components. The ReplicationServer and ApiServer now accept a timeout for their shutdown processes, allowing for either a graceful shutdown or an immediate stop based on the provided value. Additionally, the synchronization worker has been refactored to utilize goroutines and channels for non-blocking error handling, while test utilities and mocks have been updated to reflect the new shutdown signatures and improve resource management.

Changes

Files Change Summary
cmd/replication/main.go, pkg/server/server.go, pkg/api/server.go Updated shutdown method signatures to include timeout parameters; added the time package import; modified internal logic in WaitForShutdown, Shutdown, and Close to choose between graceful and immediate shutdown based on the timeout value.
pkg/server/server_test.go Simplified node subscription handling by replacing closure functions, introduced individual cancellation for node channels, and added a new Stop method in the mocks for better test resource management.
pkg/sync/syncWorker.go Refactored stream subscription and listening: declared connection variables inline, implemented non-blocking message and error handling using goroutines and channels, improving error logging and control flow.
pkg/testutils/api/api.go Modified the test API server cleanup function to call Close with an explicit timeout argument (0) instead of a parameterless call.
pkg/testutils/store.go Added a new function getCallerName that uses runtime.Caller to generate unique database names based on the caller’s function name.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant ReplicationServer
    participant ApiServer
    Main->>ReplicationServer: WaitForShutdown(10 * time.Second)
    ReplicationServer->>ApiServer: Shutdown(10 * time.Second)
    alt Graceful Shutdown
        ApiServer->>ApiServer: gracefulShutdown(timeout)
    else Immediate Shutdown
        ApiServer->>ApiServer: Stop gRPC server
    end
    ApiServer-->>ReplicationServer: Shutdown complete
    ReplicationServer-->>Main: Shutdown complete
Loading
sequenceDiagram
    participant SyncWorker
    participant recvChan
    participant errChan
    SyncWorker->>recvChan: Start listening for messages
    SyncWorker->>errChan: Start listening for errors concurrently
    alt Message Received
        recvChan->>SyncWorker: Process message
    else Error Encountered
        errChan->>SyncWorker: Log and manage error
    end
Loading

Possibly related PRs

  • Read your own group writes #415: The changes in the main PR, which involve modifying the WaitForShutdown method to include a timeout parameter, are related to the changes in the retrieved PR that also introduce timeout parameters in the Close method of the ApiServer, as both modifications enhance the shutdown control flow of their respective server implementations.
  • Wait for logs in blockchain publisher #249: The changes in the main PR, which involve modifying the WaitForShutdown method in the ReplicationServer to include a timeout parameter, are related to the changes in the retrieved PR that also involve timeout handling in the Close method of the ApiServer, as both modifications enhance shutdown control flow by introducing timeout parameters.
  • Handle registry changes #252: The changes in the main PR, specifically the modification of the WaitForShutdown method in the ReplicationServer to include a timeout parameter, are related to the changes in the retrieved PR, which also involves improvements to the shutdown processes, including context management and cancellation. Both PRs focus on enhancing the shutdown logic of server components.

Suggested reviewers

  • fbac

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 802843a and d8d2817.

📒 Files selected for processing (1)
  • pkg/sync/syncWorker.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/sync/syncWorker.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@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

🧹 Nitpick comments (6)
pkg/sync/syncWorker.go (1)

327-363: Good use of goroutines and channels for non-blocking streaming.

This approach nicely separates message reception from processing. However, if there is a high volume of envelopes, consider using a buffered channel or managing backpressure to avoid potential blocking scenarios. Otherwise, the concurrency logic looks correct and well-structured.

pkg/testutils/store.go (2)

23-33: Consider sanitizing or further trimming the function name.

getCallerName is straightforward and helpful for generating context-based names. However, if test function names contain unusual characters or become lengthy, database creation might fail in Postgres (with a 63-character limit on identifiers). Consider trimming or replacing non-alphanumeric characters to ensure reliability.


49-50: Verify length and characters of generated database names.

Prefixing "test_" plus the function name plus a 12-character random string could exceed Postgres’s identifier length limit or include invalid characters (if any appear in the test name). To prevent failures, you could truncate or sanitize the final name.

Example idea:

-dbName := "test_" + getCallerName(3) + "_" + RandomStringLower(12)
+rawName := getCallerName(3)
+safeName := sanitizeDBName(rawName) // user-implemented function
+dbName := "test_" + safeName + "_" + RandomStringLower(12)
cmd/replication/main.go (1)

141-141: Consider making the shutdown timeout configurable.

Hardcoding s.WaitForShutdown(10 * time.Second) is functional, but allowing configuration or command-line parameters could make it more flexible for different environments or testing scenarios.

pkg/api/server.go (1)

149-167: Consider adding error handling for graceful shutdown.

While the implementation is good, it might be helpful to return an error from the Close method to indicate whether the shutdown was graceful or forced.

Apply this diff to enhance error handling:

-func (s *ApiServer) Close(timeout time.Duration) {
+func (s *ApiServer) Close(timeout time.Duration) error {
 	s.log.Debug("closing")
 	if s.grpcServer != nil {
 		if timeout != 0 {
 			s.gracefulShutdown(timeout)
 		} else {
 			s.grpcServer.Stop()
 		}
 	}
 	if s.grpcListener != nil {
 		if err := s.grpcListener.Close(); err != nil && !isErrUseOfClosedConnection(err) {
 			s.log.Error("Error while closing grpc listener", zap.Error(err))
+			return fmt.Errorf("failed to close grpc listener: %w", err)
 		}
 		s.grpcListener = nil
 	}

 	s.wg.Wait()
 	s.log.Debug("closed")
+	return nil
}
pkg/server/server.go (1)

264-269: Consider adding signal handling timeout.

While propagating the timeout to Shutdown is good, the signal handling itself could benefit from a timeout to prevent hanging indefinitely.

Apply this diff to add signal handling timeout:

 func (s *ReplicationServer) WaitForShutdown(timeout time.Duration) {
 	termChannel := make(chan os.Signal, 1)
 	signal.Notify(termChannel, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
-	<-termChannel
+	select {
+	case <-termChannel:
+	case <-time.After(timeout):
+		s.log.Warn("Shutdown timeout reached while waiting for signal")
+	}
 	s.Shutdown(timeout)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5f81ec and 802843a.

📒 Files selected for processing (7)
  • cmd/replication/main.go (2 hunks)
  • pkg/api/server.go (1 hunks)
  • pkg/server/server.go (3 hunks)
  • pkg/server/server_test.go (2 hunks)
  • pkg/sync/syncWorker.go (2 hunks)
  • pkg/testutils/api/api.go (1 hunks)
  • pkg/testutils/store.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
pkg/sync/syncWorker.go

204-204: ineffectual assignment to err

(ineffassign)

🪛 GitHub Check: Lint-Go
pkg/sync/syncWorker.go

[failure] 204-204:
ineffectual assignment to err (ineffassign)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)
🔇 Additional comments (6)
pkg/api/server.go (1)

132-147: LGTM! Well-structured graceful shutdown implementation.

The implementation correctly handles both graceful and forced shutdown scenarios using concurrent goroutines and context cancellation for coordination.

pkg/testutils/api/api.go (1)

167-167: LGTM! Appropriate use of immediate shutdown for test cleanup.

Using timeout=0 is correct for test scenarios where we want immediate cleanup without waiting for graceful shutdown.

pkg/server/server.go (1)

271-292: LGTM! Well-structured component shutdown sequence.

The shutdown sequence is correct, closing components in a logical order and propagating the timeout to the API server.

pkg/server/server_test.go (3)

143-146: LGTM! Proper test cleanup with immediate shutdown.

Using timeout=0 ensures quick and deterministic test cleanup.


122-131: LGTM! Improved node change notification handling.

The separate channels with individual cleanup functions improve test isolation and prevent cross-contamination of notifications between nodes.


136-136: LGTM! Added mock Stop method.

The Stop method mock correctly implements the registry interface.

@mkysel mkysel merged commit 35c421e into main Feb 12, 2025
7 checks passed
@mkysel mkysel deleted the mkysel/improvements branch February 12, 2025 13:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants