Skip to content

refactor(notification): error handling - #3008

Merged
chrisgacsal merged 4 commits into
mainfrom
fix/notification
Jun 19, 2025
Merged

chrisgacsal merged 4 commits into
mainfrom
fix/notification

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Jun 18, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

  • refactor event payload mapping
  • refactor svix error mapping
  • refactor validation errors
  • fix handling conflict error when sendin message which has been already dispatched to svix

Summary by CodeRabbit

  • New Features

    • Improved error reporting for webhook validation and Svix webhook interactions, providing more detailed and structured error messages.
    • Validation methods now report all input errors at once, rather than stopping at the first error.
  • Bug Fixes

    • Enhanced error handling for webhook message sending and application creation, including specific handling for conflict and validation errors.
  • Refactor

    • Modularized event reconciliation and webhook payload preparation for better maintainability.
    • Centralized and unified validation and error handling logic for webhooks.
  • Chores

    • Updated internal error handling for third-party integrations to improve reliability and clarity.

@chrisgacsal chrisgacsal self-assigned this Jun 18, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner June 18, 2025 14:39
@chrisgacsal chrisgacsal added release-note/bug-fix Release note: Bug Fixes kind/refactor Code refactor, cleanup or minor improvement labels Jun 18, 2025
@coderabbitai

coderabbitai Bot commented Jun 18, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update restructures notification and webhook handling by extracting event-to-payload conversion into a helper, modularizing event reconciliation, and centralizing Svix error handling in a new internal package. Validation logic is unified to aggregate errors, and secret validation is moved to a dedicated file. Svix webhook integration now uses structured error parsing and improved conflict handling.

Changes

Files/Paths Change Summary
openmeter/notification/eventhandler/dispatch.go Extracted event-to-payload logic into eventAsPayload; simplified dispatchWebhook to use the helper.
openmeter/notification/eventhandler/reconcile.go Added reconcileEvent method; refactored Reconcile to use it and aggregate errors per event.
openmeter/notification/httpdriver/errors.go Changed HTTP error encoder to return 500 for webhook.ValidationError instead of 400.
openmeter/notification/webhook/errors.go Refactored ValidationError to a struct; added NewValidationError constructor; removed genericError.
openmeter/notification/webhook/handler.go Refactored input validation to aggregate errors; removed ValidateSigningSecret and related imports.
openmeter/notification/webhook/secret.go Added SigningSecretPrefix and new ValidateSigningSecret function for secret validation.
openmeter/notification/webhook/svix/application.go Introduced CreateApplication method for creating/retrieving Svix applications.
openmeter/notification/webhook/svix/event.go Switched error handling to use internal.AsSvixError for Svix event type updates.
openmeter/notification/webhook/svix/internal/error.go New file: Implements SvixError type, error parsing, and AsSvixError function for structured Svix error handling.
openmeter/notification/webhook/svix/message.go Enhanced error handling in SendMessage; added getMessage for conflict resolution and structured error returns.
openmeter/notification/webhook/svix/svix.go Removed local error handling and CreateApplication; aliased Error to internal type.
openmeter/notification/webhook/svix/webhook.go Replaced all error handling with internal.AsSvixError for endpoint operations.

Possibly related PRs

  • fix: notification issues/test message #2763: Refactors notification event payload conversion and test message generation, directly relating to improvements in event payload handling and notification robustness in this PR.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (6)
openmeter/notification/webhook/svix/event.go (1)

23-26: Log message says “create” while the call performs an “update”

EventType.Update is invoked but the wrapped error reads “failed to create event type”, which is confusing when troubleshooting.

-			return fmt.Errorf("failed to create event type: %w", err)
+			return fmt.Errorf("failed to update event type %q: %w", eventType.Name, err)
openmeter/notification/webhook/secret.go (1)

30-43: Early-exit to avoid allocating/wrapping when no validation errors

errors.Join(nil) already returns nil, but we still allocate a slice and call NewValidationError.
A quick short-circuit keeps the happy path cheaper and simpler.

-	var errs []error
+	var errs []error
 ...
-	return NewValidationError(errors.Join(errs...))
+if len(errs) == 0 {
+	return nil
+}
+
+return NewValidationError(errors.Join(errs...))
openmeter/notification/webhook/errors.go (1)

17-23: Guard against double-wrapping ValidationError

If callers accidentally pass an existing ValidationError to NewValidationError, it will be wrapped again, breaking errors.Is/As checks.
Consider short-circuiting when errors.As(err, &ValidationError{}) is true.

 func NewValidationError(err error) error {
 	if err == nil {
 		return nil
 	}
+
+	var ve ValidationError
+	if errors.As(err, &ve) { // already wrapped
+		return err
+	}
 
 	return ValidationError{err: err}
 }
openmeter/notification/webhook/svix/webhook.go (1)

27-37: Repeated internal.AsSvixError pattern can be centralised

Almost every SDK call now follows:

err := client.Foo(...)
if err = internal.AsSvixError(err); err != nil {
    return ..., fmt.Errorf("failed to ...: %w", err)
}

Extracting this into a tiny helper (or embedding client in a thin wrapper) would:

• remove duplication
• ensure future calls follow the same policy
• keep individual handlers focused on business logic.

No functional change required, but worth considering for maintainability.

Also applies to: 70-76, 239-243, 331-334, 345-347, 371-373

openmeter/notification/webhook/svix/application.go (1)

14-17: Consider differentiating between Name and Uid fields

While setting both Name and Uid to the same value works, it might be semantically clearer to use a more descriptive name. Consider whether these should be different values for better clarity.

 input := svix.ApplicationIn{
-    Name: id,
+    Name: fmt.Sprintf("Application %s", id),
     Uid:  &id,
 }
openmeter/notification/webhook/svix/internal/error.go (1)

63-65: Consider adding context when JSON unmarshaling fails.

When JSON unmarshaling fails, the function returns the original error without indicating that parsing failed. This could make debugging more difficult.

Consider wrapping the error with additional context:

 		if e := json.Unmarshal(svixErr.Body(), &body); e != nil {
-			return err
+			return fmt.Errorf("failed to parse svix validation error response: %w", err)
 		}

And similarly for the default case:

 		if e := json.Unmarshal(svixErr.Body(), &body); e != nil {
-			return err
+			return fmt.Errorf("failed to parse svix error response: %w", err)
 		}

Note: This change requires adding "fmt" to the imports if not already present (which it already is in this file).

Also applies to: 76-78

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 739e0d9 and f54a010.

📒 Files selected for processing (12)
  • openmeter/notification/eventhandler/dispatch.go (1 hunks)
  • openmeter/notification/eventhandler/reconcile.go (2 hunks)
  • openmeter/notification/httpdriver/errors.go (1 hunks)
  • openmeter/notification/webhook/errors.go (1 hunks)
  • openmeter/notification/webhook/handler.go (6 hunks)
  • openmeter/notification/webhook/secret.go (2 hunks)
  • openmeter/notification/webhook/svix/application.go (1 hunks)
  • openmeter/notification/webhook/svix/event.go (2 hunks)
  • openmeter/notification/webhook/svix/internal/error.go (1 hunks)
  • openmeter/notification/webhook/svix/message.go (3 hunks)
  • openmeter/notification/webhook/svix/svix.go (2 hunks)
  • openmeter/notification/webhook/svix/webhook.go (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Commit hooks
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/notification/webhook/svix/application.go (1)

13-32: LGTM! Clean implementation with proper error handling

The method correctly implements application creation with idempotency support and follows the new error handling pattern consistently.

openmeter/notification/eventhandler/dispatch.go (2)

15-54: Excellent refactoring - improves separation of concerns

The extraction of payload conversion logic into a dedicated helper function enhances code readability and maintainability. The error handling is consistent and comprehensive.


56-61: Clean integration with the new helper function

The simplified dispatchWebhook method now focuses solely on webhook dispatch logic, making the code more maintainable.

openmeter/notification/webhook/svix/svix.go (1)

17-17: Good consolidation of error handling

The use of a type alias to internal.SvixError maintains API compatibility while centralizing the error handling implementation. This aligns well with the PR's objective of improving error handling.

Also applies to: 30-30

openmeter/notification/webhook/svix/message.go (2)

42-58: Excellent improvement to conflict handling

The enhanced error handling now properly differentiates between error types and implements idempotent behavior by retrieving existing messages on conflicts. This is a significant improvement that aligns with the PR's goal of better error handling.


70-97: Well-structured helper method with consistent error handling

The getMessage helper maintains consistency with the error handling pattern established in SendMessage and properly includes content in the response.

openmeter/notification/eventhandler/reconcile.go (2)

26-47: Good modularization of reconciliation logic

The extraction of event reconciliation into a dedicated method improves code organization and makes the logic easier to test and maintain.


61-72: Improved error handling with better context

The change from fail-fast to error accumulation allows all events to be processed, and the enhanced error messages with namespace and event ID provide valuable debugging context.

openmeter/notification/webhook/handler.go (1)

40-48: Excellent refactor of validation error handling!

The consistent pattern of accumulating all validation errors and returning them together significantly improves the user experience. Users can now see all validation issues at once instead of discovering them one by one.

Also applies to: 67-85, 104-128, 140-152, 162-174, 199-215

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/refactor Code refactor, cleanup or minor improvement release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants