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

Propagate bacerrors over nclprotocol #4774

Merged
merged 2 commits into from
Dec 16, 2024

Conversation

wdbaruni
Copy link
Member

@wdbaruni wdbaruni commented Dec 16, 2024

Summary by CodeRabbit

  • New Features

    • Introduced JSON serialization and deserialization for error handling.
    • Added standardized error handling mechanisms using the bacerrors package.
    • Implemented new error reporting functions for connection management.
  • Bug Fixes

    • Enhanced error handling logic in various components, improving robustness and clarity.
  • Tests

    • Added comprehensive unit tests for JSON marshalling and unmarshalling of error structures.
  • Chores

    • Updated import statements across multiple files to include the bacerrors package.

Copy link

linear bot commented Dec 16, 2024

@wdbaruni wdbaruni self-assigned this Dec 16, 2024
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces a comprehensive update to error handling across multiple packages in the Bacalhau project. The changes primarily focus on implementing a new error serialization mechanism using the bacerrors package, which provides more structured and consistent error reporting. The modifications span several files, introducing JSON serialization for errors, updating error response handling, and refactoring error management in various components of the system, particularly in network communication and node management.

Changes

File Change Summary
pkg/bacerrors/json.go Added JSON marshalling and unmarshalling methods for errorImpl struct
pkg/bacerrors/json_test.go Added comprehensive unit tests for JSON error serialization
pkg/lib/ncl/encoder.go Updated error response registration to use bacerrors package
pkg/lib/ncl/encoder_test.go Modified error handling in tests to use new bacerrors approach
pkg/lib/ncl/error_response.go Removed old ErrorResponse struct, added BacErrorToEnvelope function
pkg/lib/ncl/publisher.go Updated error handling to use bacerrors
pkg/lib/ncl/responder.go Modified error response methods to work with bacerrors
pkg/transport/nclprotocol/... Various error handling improvements across components

Sequence Diagram

sequenceDiagram
    participant Client
    participant Encoder
    participant ErrorHandler
    participant Responder

    Client->>Encoder: Send Request
    Encoder->>ErrorHandler: Process Request
    alt Request Successful
        ErrorHandler-->>Encoder: Return Response
    else Request Fails
        ErrorHandler->>Responder: Create Bacalhau Error
        Responder->>Encoder: Serialize Error
        Encoder->>Client: Return Serialized Error
    end
Loading

Poem

🐰 Errors dance in JSON light,
Wrapped with care, both wrong and right,
Bacalhau's magic now unfurled,
Serialized errors rule the world!
Code hops cleaner, errors bright! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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
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 comments (2)
pkg/lib/ncl/encoder.go (1)

Line range hint 44-48: Fix error handling logic

The error handling seems incorrect. The condition checks for ErrAlreadyRegistered but returns an error in that case while ignoring other errors.

     if err := config.messageRegistry.Register(BacErrorMessageType, bacerrors.New("")); err != nil {
-        if errors.Is(err, envelope.ErrAlreadyRegistered{}) {
+        if !errors.Is(err, envelope.ErrAlreadyRegistered{}) {
             return nil, fmt.Errorf("failed to register error response type: %w", err)
         }
     }
pkg/lib/ncl/responder.go (1)

Line range hint 146-162: Fix error message formatting.

The error message in bacerrors.New uses a format string but the arguments are passed incorrectly.

Apply this fix:

-		r.sendErrorResponse(requestMsg, bacerrors.New("no handler found for message type: %s", messageType).
+		r.sendErrorResponse(requestMsg, bacerrors.Newf("no handler found for message type: %s", messageType).
🧹 Nitpick comments (9)
pkg/bacerrors/json.go (2)

7-17: LGTM! Consider enhancing documentation.

The JSONError struct is well-structured with appropriate fields and JSON tags. Consider adding field-level documentation to describe the purpose of each field, especially for fields like FailsExecution where the implications might not be immediately obvious.


33-50: Consider adding validation for critical fields.

While the unmarshaling implementation is correct, consider adding validation for critical fields like HTTPStatusCode (should be > 0) and Code (should be a valid ErrorCode). This would prevent invalid error states.

 func (e *errorImpl) UnmarshalJSON(data []byte) error {
 	var je JSONError
 	if err := json.Unmarshal(data, &je); err != nil {
 		return err
 	}
+
+	// Validate critical fields
+	if je.HTTPStatusCode <= 0 {
+		return fmt.Errorf("invalid HTTP status code: %d", je.HTTPStatusCode)
+	}
+	if !je.Code.IsValid() { // Assuming ErrorCode has a validation method
+		return fmt.Errorf("invalid error code: %s", je.Code)
+	}

 	e.cause = je.Cause
 	e.hint = je.Hint
pkg/lib/ncl/error_response.go (1)

21-29: Consider using a consistent time source.

The BacErrorToEnvelope function uses time.Now() directly, which could lead to inconsistencies in distributed systems. Consider accepting the event time as a parameter or using a centralized time source.

-func BacErrorToEnvelope(err bacerrors.Error) *envelope.Message {
+func BacErrorToEnvelope(err bacerrors.Error, eventTime time.Time) *envelope.Message {
 	errMsg := envelope.NewMessage(err)
 	errMsg.WithMetadataValue(envelope.KeyMessageType, BacErrorMessageType)
 	errMsg.WithMetadataValue(KeyStatusCode, fmt.Sprintf("%d", err.HTTPStatusCode()))
 	errMsg.WithMetadataValue(KeyErrorCode, string(err.Code()))
-	errMsg.WithMetadataValue(KeyEventTime, time.Now().Format(time.RFC3339))
+	errMsg.WithMetadataValue(KeyEventTime, eventTime.Format(time.RFC3339))
 	return errMsg
 }
pkg/transport/nclprotocol/orchestrator/errors.go (1)

8-14: LGTM! Consider adding error documentation.

The implementation correctly extends the base error with component information. Consider adding a package-level documentation comment explaining the error types and their usage patterns in this package.

pkg/bacerrors/json_test.go (2)

75-81: Enhance invalid JSON test cases

The current invalid JSON test only covers one scenario. Consider adding more test cases:

  • Missing required fields
  • Invalid field types for other fields
  • Malformed JSON syntax
  • Empty JSON object
 func TestErrorJSONMarshallingInvalid(t *testing.T) {
-    // Test unmarshalling invalid JSON
-    invalidJSON := []byte(`{"Cause": "test", "Retryable": "invalid"}`)
-    var unmarshaled errorImpl
-    err := json.Unmarshal(invalidJSON, &unmarshaled)
-    assert.Error(t, err, "Should fail to unmarshal invalid JSON")
+    testCases := []struct {
+        name string
+        json string
+    }{
+        {
+            name: "invalid boolean",
+            json: `{"Cause": "test", "Retryable": "invalid"}`,
+        },
+        {
+            name: "missing required cause",
+            json: `{"Retryable": true}`,
+        },
+        {
+            name: "malformed json",
+            json: `{"Cause": "test" "Retryable": true}`,
+        },
+        {
+            name: "empty object",
+            json: `{}`,
+        },
+    }
+
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
+            var unmarshaled errorImpl
+            err := json.Unmarshal([]byte(tc.json), &unmarshaled)
+            assert.Error(t, err, "Should fail to unmarshal invalid JSON")
+        })
+    }
 }

13-47: Add test for error chain serialization

The current test doesn't verify how wrapped errors are handled during serialization. Consider adding test cases for:

  • Wrapped errors with multiple levels
  • Circular error references
pkg/lib/ncl/encoder.go (1)

44-44: Reconsider using empty string in bacerrors.New

Using bacerrors.New("") for type registration seems questionable. Consider:

  1. Using a meaningful placeholder message
  2. Creating a dedicated method for type registration that doesn't require a message
-    if err := config.messageRegistry.Register(BacErrorMessageType, bacerrors.New("")); err != nil {
+    if err := config.messageRegistry.Register(BacErrorMessageType, bacerrors.New("type_registration_placeholder")); err != nil {
pkg/lib/ncl/publisher.go (1)

98-98: Avoid using empty string in bacerrors.New

Similar to the encoder, using bacerrors.New("") for type checking seems questionable.

-    if errorResponse, ok := message.GetPayload(bacerrors.New("")); ok {
+    if errorResponse, ok := message.GetPayload(bacerrors.New("type_check_placeholder")); ok {
pkg/transport/nclprotocol/compute/controlplane.go (1)

Line range hint 109-113: Consider enhancing error handling in the heartbeat method.

While the handshake error check is improved, consider wrapping the heartbeat error with bacerrors for consistency.

Consider applying this enhancement:

-				log.Error().Err(err).Msg("Failed to send heartbeat")
+				log.Error().Err(bacerrors.Wrap(err, "heartbeat failed")).Msg("Failed to send heartbeat")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 823e9e9 and fdd9421.

📒 Files selected for processing (10)
  • pkg/bacerrors/json.go (1 hunks)
  • pkg/bacerrors/json_test.go (1 hunks)
  • pkg/lib/ncl/encoder.go (2 hunks)
  • pkg/lib/ncl/encoder_test.go (2 hunks)
  • pkg/lib/ncl/error_response.go (1 hunks)
  • pkg/lib/ncl/publisher.go (2 hunks)
  • pkg/lib/ncl/responder.go (5 hunks)
  • pkg/transport/nclprotocol/compute/controlplane.go (2 hunks)
  • pkg/transport/nclprotocol/orchestrator/errors.go (1 hunks)
  • pkg/transport/nclprotocol/orchestrator/manager.go (3 hunks)
🔇 Additional comments (9)
pkg/bacerrors/json.go (1)

19-31: LGTM!

The MarshalJSON implementation correctly maps all fields from errorImpl to JSONError for serialization.

pkg/lib/ncl/encoder_test.go (2)

11-11: LGTM: Import aligns with the new error handling approach.

The addition of the bacerrors package import supports the transition to structured error handling.


181-192: LGTM: Test updates properly validate the new error handling mechanism.

The test changes effectively verify:

  • Error creation with specific error codes
  • Proper encoding/decoding of structured errors
  • Correct error code and message preservation
pkg/lib/ncl/responder.go (2)

187-196: LGTM: Improved error handling for response encoding failures.

The changes properly handle encoding failures differently for error responses vs normal responses, preventing infinite error response loops.


213-214: LGTM: Clean signature update for error handling.

The method signature change to use bacerrors.Error aligns with the new error handling approach.

pkg/transport/nclprotocol/compute/controlplane.go (1)

11-11: LGTM: Imports support improved error handling.

The addition of bacerrors and nodes packages properly supports the new error handling mechanism.

Also applies to: 16-16

pkg/transport/nclprotocol/orchestrator/manager.go (3)

251-251: LGTM: Improved error handling for missing data plane

The change from string formatting to NewErrHandshakeRequired provides more structured error handling while maintaining the same logical flow.


274-274: LGTM: Consistent error handling approach

The change maintains consistency with other handlers by using NewErrHandshakeRequired for missing data plane scenarios.


296-296: Verify handshake requirement during shutdown

While the change to NewErrHandshakeRequired maintains consistency with other handlers, please verify if requiring a handshake during shutdown is the intended behavior. A node might legitimately need to send a shutdown notice even if its data plane is no longer active.

Let's verify the shutdown behavior in the codebase:

pkg/lib/ncl/publisher.go Show resolved Hide resolved
@wdbaruni wdbaruni merged commit 9135124 into main Dec 16, 2024
14 checks passed
@wdbaruni wdbaruni deleted the eng-452-propagate-bacerrors-over-ncl branch December 16, 2024 12:52
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.

1 participant