Skip to content

refactor(notification): webhook handler - #2767

Merged
chrisgacsal merged 3 commits into
mainfrom
refactor/notification
May 6, 2025
Merged

chrisgacsal merged 3 commits into
mainfrom
refactor/notification

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented May 3, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Restructure the webhook package of notification service. No change in the business logic.

Summary by CodeRabbit

  • Refactor

    • Introduced a dedicated Svix-based webhook handler with comprehensive webhook lifecycle and messaging support.
    • Moved the no-operation webhook handler to its own package for clearer separation.
    • Split webhook handler interfaces into focused components for event type registration, webhook management, and messaging.
    • Renamed "Repository" to "Adapter" in notification service for improved clarity.
    • Modularized event type registration and message sending in webhook handling.
    • Extracted webhook handler initialization into a dedicated constructor, enhancing notification service setup.
  • Bug Fixes

    • Enhanced error handling and validation during webhook and notification service initialization.
  • Chores

    • Updated test suites and internal configurations to use dynamic namespaces and the new Svix webhook handler.
    • Adjusted test inputs and assertions to accommodate namespace parameterization and handler changes.

@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label May 3, 2025
@chrisgacsal chrisgacsal self-assigned this May 3, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner May 3, 2025 05:06
@coderabbitai

coderabbitai Bot commented May 3, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change refactors the notification webhook handler implementation, separating the Svix-based and no-op webhook handlers into distinct packages and files. The Svix handler is now located under openmeter/notification/webhook/svix, with its configuration, initialization, and all webhook management methods moved and restructured. The no-op handler is relocated to openmeter/notification/webhook/noop. The notification service wiring and construction are updated to use a dedicated constructor for the webhook handler, which is passed as a dependency. Configuration references and type aliases are updated to use the new Svix package. The notification service struct and related code are also updated to use the term "Adapter" instead of "Repository" for clarity.

Changes

Files / Groups Change Summary
app/common/config.go Extended the Wire provider set to explicitly include the Webhook configuration fields from config.NotificationConfiguration.
app/common/notification.go Extracted webhook handler initialization into a new NewNotificationWebhookHandler constructor; updated NewNotificationService to accept a pre-initialized webhook handler; adjusted Wire provider set and error handling accordingly.
app/config/config_test.go, app/config/svix.go Updated Svix configuration type imports and references to use the new svix package instead of the previous webhook package.
cmd/notification-service/wire_gen.go, cmd/server/wire_gen.go Refactored notification service initialization to separately create a webhook handler from configuration, pass it to the service constructor, and handle errors with appropriate cleanup.
openmeter/notification/service/service.go Renamed Repository field and references to Adapter in the Config struct and New function.
openmeter/notification/webhook/handler.go Refactored the handler interface: split the original Handler into EventTypeHandler, WebhookHandler, and MessageHandler interfaces; introduced a composite Handler interface; removed the Config struct and the New constructor function.
openmeter/notification/webhook/noop.go Deleted the original no-op webhook handler implementation.
openmeter/notification/webhook/noop/noop.go Added a new no-op webhook handler in a separate package, implementing the webhook.Handler interface with stub methods and contextual logging.
openmeter/notification/webhook/svix.go Deleted the original Svix webhook handler implementation, including its configuration, handler struct, methods, and utility functions.
openmeter/notification/webhook/svix/svix.go Introduced a new Svix webhook handler package with configuration structs, validation, handler initialization, application creation, idempotency key generation, and error unwrapping utilities.
openmeter/notification/webhook/svix/event.go Added method to register event types with Svix, handling updates and error wrapping.
openmeter/notification/webhook/svix/message.go Added method to send messages via Svix, with input validation, idempotency key generation, and error handling.
openmeter/notification/webhook/svix/webhook.go Implemented full webhook lifecycle management (create, update, delete, retrieve, list), secret and header management, and filtering for the Svix handler.
test/notification/testenv.go Updated to use the new Svix webhook handler package and configuration; renamed variables from repo to adapter and updated service initialization accordingly.
openmeter/notification/consumer/entitlementbalancethreshold.go, openmeter/notification/consumer/entitlementreset.go Changed error aggregation from incremental errors.Join calls to collecting errors in a slice and joining once at the end in event handling methods.
test/notification/channel.go, test/notification/consumer_balance.go, test/notification/event.go, test/notification/rule.go, test/notification/webhook.go Updated test input constructors to accept dynamic namespace parameters instead of a fixed TestNamespace; updated test calls accordingly to use environment namespace.
test/notification/notification_test.go, test/notification/repository.go Replaced static namespace usage with dynamic environment namespace retrieval in test setup and repository initialization.

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


📜 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 75a309f and 3181e37.

📒 Files selected for processing (25)
  • app/common/config.go (1 hunks)
  • app/common/notification.go (2 hunks)
  • app/config/config_test.go (2 hunks)
  • app/config/svix.go (1 hunks)
  • cmd/notification-service/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/notification/consumer/entitlementbalancethreshold.go (1 hunks)
  • openmeter/notification/consumer/entitlementreset.go (1 hunks)
  • openmeter/notification/service/service.go (3 hunks)
  • openmeter/notification/webhook/handler.go (1 hunks)
  • openmeter/notification/webhook/noop.go (0 hunks)
  • openmeter/notification/webhook/noop/noop.go (1 hunks)
  • openmeter/notification/webhook/svix.go (0 hunks)
  • openmeter/notification/webhook/svix/event.go (1 hunks)
  • openmeter/notification/webhook/svix/message.go (1 hunks)
  • openmeter/notification/webhook/svix/svix.go (1 hunks)
  • openmeter/notification/webhook/svix/webhook.go (1 hunks)
  • test/notification/channel.go (6 hunks)
  • test/notification/consumer_balance.go (3 hunks)
  • test/notification/event.go (9 hunks)
  • test/notification/notification_test.go (1 hunks)
  • test/notification/repository.go (1 hunks)
  • test/notification/rule.go (5 hunks)
  • test/notification/testenv.go (9 hunks)
  • test/notification/webhook.go (7 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/notification/webhook/noop.go
  • openmeter/notification/webhook/svix.go
🚧 Files skipped from review as they are similar to previous changes (22)
  • cmd/notification-service/wire_gen.go
  • test/notification/repository.go
  • test/notification/notification_test.go
  • openmeter/notification/consumer/entitlementbalancethreshold.go
  • openmeter/notification/consumer/entitlementreset.go
  • app/config/svix.go
  • cmd/server/wire_gen.go
  • app/config/config_test.go
  • app/common/config.go
  • test/notification/rule.go
  • test/notification/consumer_balance.go
  • test/notification/channel.go
  • openmeter/notification/service/service.go
  • openmeter/notification/webhook/handler.go
  • test/notification/event.go
  • openmeter/notification/webhook/svix/message.go
  • test/notification/webhook.go
  • test/notification/testenv.go
  • openmeter/notification/webhook/svix/event.go
  • app/common/notification.go
  • openmeter/notification/webhook/noop/noop.go
  • openmeter/notification/webhook/svix/svix.go
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
openmeter/notification/webhook/svix/webhook.go (5)

444-444: The ListWebhooks now correctly appends results to the return slice

The implementation now properly appends webhooks to the result slice, fixing the previous issue where it always returned an empty slice.


390-420: Filter logic correctly handles the empty filter case

The implementation now returns all webhooks when no filters are specified, fixing the previous behavior where it would return an empty list.


108-112: Channel fallback prevents unintended webhook triggers

Good defensive programming practice to add a null channel when no event types or channels are specified. This prevents webhooks from receiving all messages by default and allows for more controlled webhook behavior.


450-464: WebhookFromSvixEndpointOut correctly filters out null channels

The implementation properly removes the null channel from the returned webhook, ensuring that clients only see meaningful channel configurations.


310-314: Ensure there's always at least one channel configured

Good defensive programming check to ensure that removing all channels still results in a valid webhook configuration by adding the null channel.

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

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.

@chrisgacsal
chrisgacsal requested review from hekike, tothandras and turip May 3, 2025 05:06

@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: 6

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

210-220: Optional: surface JSON-parsing failures when unwrapping Svix errors
json.Unmarshal errors are silently ignored. While this is harmless today, it can mask schema changes in Svix error bodies. If you log (at debug) or wrap that parse failure, diagnosing future issues becomes easier.

app/config/config_test.go (1)

14-18: Import alias consistency
After the refactor you now import both
notificationwebhook and svix. Only notificationwebhook.DefaultRegistrationTimeout is referenced. If future cleanup removes that constant from the parent package this test will break.
Consider referencing the constant from the new package as well (or re-export it) to keep the import list minimal.

app/common/notification.go (1)

52-73: Constructor correctly isolates webhook selection logic – minor safety tweaks suggested

Solid extraction! Two small follow-ups you may want to consider:

  1. NewNotificationWebhookHandler currently decides on the Svix/no-op branch purely via svixConfig.IsEnabled().
    – If the Svix block is taken but webhooksvix.New fails (mis-configuration, network, …) the service build will abort. That’s fine, but consider logging the parameters that led to the failure to ease diagnosis (logger.Error(...)).
  2. The function returns a concrete instance but does not wrap the error with errors.WithStack or similar. If you already use a stack-aware error package elsewhere, wrap it here for consistency.

Nothing blocking – just small hardening ideas.

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

32-36: Returning hard-coded “not implemented” errors may break the call-sites

The noop implementation is intended for deployments where webhooks are disabled.
Returning a generic fmt.Errorf("create webhook: not implemented") (and similar) might bubble up and break admin UIs or background jobs that expect success even when webhooks are disabled.

Consider returning a sentinel error that callers can explicitly ignore, e.g.

var ErrWebhookDisabled = errors.New("webhook feature disabled")

and documenting the contract (e.g. create/update/delete may return ErrWebhookDisabled, list returns empty slice).
This guards the system against unexpected 500’s while still signalling the real status to interested callers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 06eaf89 and 1ef7322.

📒 Files selected for processing (16)
  • app/common/config.go (1 hunks)
  • app/common/notification.go (2 hunks)
  • app/config/config_test.go (2 hunks)
  • app/config/svix.go (1 hunks)
  • cmd/notification-service/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/notification/service/service.go (3 hunks)
  • openmeter/notification/webhook/handler.go (1 hunks)
  • openmeter/notification/webhook/noop.go (0 hunks)
  • openmeter/notification/webhook/noop/noop.go (1 hunks)
  • openmeter/notification/webhook/svix.go (0 hunks)
  • openmeter/notification/webhook/svix/event.go (1 hunks)
  • openmeter/notification/webhook/svix/message.go (1 hunks)
  • openmeter/notification/webhook/svix/svix.go (1 hunks)
  • openmeter/notification/webhook/svix/webhook.go (1 hunks)
  • test/notification/testenv.go (5 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/notification/webhook/noop.go
  • openmeter/notification/webhook/svix.go
🧰 Additional context used
🧬 Code Graph Analysis (5)
app/config/config_test.go (2)
app/config/svix.go (1)
  • SvixConfig (7-7)
openmeter/notification/webhook/svix/svix.go (1)
  • SvixConfig (30-35)
app/common/config.go (1)
app/config/notification.go (1)
  • NotificationConfiguration (20-24)
app/config/svix.go (1)
openmeter/notification/webhook/svix/svix.go (1)
  • SvixConfig (30-35)
openmeter/notification/webhook/noop/noop.go (1)
openmeter/notification/webhook/handler.go (11)
  • Handler (278-282)
  • RegisterEventTypesInputs (242-245)
  • CreateWebhookInput (56-69)
  • Webhook (16-30)
  • UpdateWebhookInput (97-110)
  • UpdateWebhookChannelsInput (149-155)
  • DeleteWebhookInput (197-197)
  • GetWebhookInput (175-179)
  • ListWebhooksInput (38-44)
  • SendMessageInput (211-218)
  • Message (199-207)
openmeter/notification/webhook/svix/webhook.go (3)
openmeter/notification/webhook/handler.go (7)
  • CreateWebhookInput (56-69)
  • Webhook (16-30)
  • UpdateWebhookInput (97-110)
  • UpdateWebhookChannelsInput (149-155)
  • GetWebhookInput (175-179)
  • DeleteWebhookInput (197-197)
  • ListWebhooksInput (38-44)
openmeter/notification/webhook/svix/svix.go (2)
  • NullChannel (27-27)
  • New (81-116)
pkg/convert/ptr.go (1)
  • SafeDeRef (29-34)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
app/config/svix.go (1)

3-8: LGTM – canonical re-export
Re-exporting SvixConfig through the config package maintains backwards compatibility and keeps callers decoupled from internal path changes.

cmd/notification-service/wire_gen.go (1)

137-149: Handler initialization now properly separated from service

The refactoring extracts webhook handler initialization from the notification service constructor, creating a clearer separation of concerns. This is a good architectural improvement that establishes better dependency management.

app/common/config.go (1)

36-36: Wire configuration updated to support refactored webhook handler

The addition of webhook configuration from the notification configuration ensures proper dependency injection for the new webhook handler structure. This change correctly wires up the configuration needed by the new initialization flow.

cmd/server/wire_gen.go (1)

400-413: Notification webhook handler properly extracted in server initialization

Similar to the notification service wire changes, this modification properly extracts the webhook handler initialization and adds appropriate error handling. The consistency between both wire files is maintained.

openmeter/notification/service/service.go (4)

39-40: Renamed 'Repository' to 'Adapter' for better clarity

Renaming the field from 'Repository' to 'Adapter' better reflects its role in the architecture. The addition of explicit webhook handler dependency improves code clarity.


46-48: Validation check updated for renamed field

The validation check is properly updated to use the renamed field while maintaining the same error message.


63-66: Event handler initialization updated with renamed field

The event handler initialization is correctly updated to use the renamed field while maintaining the existing functionality.


76-77: Service struct field assignment updated

The service struct initialization is properly updated to use the renamed field.

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

12-31: Clean and well-structured implementation

The RegisterEventTypes method correctly implements the webhook.EventTypeHandler interface for the Svix implementation. The code properly handles event type registration with appropriate error handling.

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

261-282: Good interface segregation

Splitting the original Handler interface into three specialized interfaces (EventTypeHandler, WebhookHandler, MessageHandler) follows the Interface Segregation Principle from SOLID. This makes the code more modular and allows implementations to focus on specific responsibilities.

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

14-53: Well-implemented message sending logic

The SendMessage method has a good implementation with proper validation, error handling, and mapping between Svix and internal data structures. The use of idempotency keys is a good practice to prevent duplicate messages.

test/notification/testenv.go (5)

17-17: Updated import for the new Svix package

The import correctly references the new package location for the Svix webhook implementation.


117-123: Renamed Repository to Adapter for clarity

The variable renaming from "repo" to "adapter" is consistent with the terminology changes across the codebase.


137-144: Updated webhook initialization to use the new Svix package

The webhook initialization has been correctly updated to use the dedicated Svix implementation.


150-151: Updated service configuration to use Adapter terminology

The notification service configuration now correctly uses Adapter instead of Repository.


178-179: Updated test environment to use the new adapter variable

The test environment initialization correctly uses the adapter variable instead of repo.

@chrisgacsal
chrisgacsal marked this pull request as draft May 3, 2025 05:32
@chrisgacsal
chrisgacsal force-pushed the refactor/notification branch 2 times, most recently from 8b77584 to 75a309f Compare May 5, 2025 15:00
@chrisgacsal
chrisgacsal marked this pull request as ready for review May 6, 2025 09:26
turip
turip previously approved these changes May 6, 2025

@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: 1

🔭 Outside diff range comments (4)
test/notification/rule.go (4)

161-167: ⚠️ Potential issue

Missing namespace parameter in TestList function calls.

The calls to NewCreateRuleInput in the list test don't include the namespace parameter that was added to the function signature.

Apply this diff to fix the issue:

-	createIn1 := NewCreateRuleInput("NotificationListRule1", s.channel.ID)
+	createIn1 := NewCreateRuleInput(s.Env.Namespace(), "NotificationListRule1", s.channel.ID)

-	createIn2 := NewCreateRuleInput("NotificationListRule2", s.channel.ID)
+	createIn2 := NewCreateRuleInput(s.Env.Namespace(), "NotificationListRule2", s.channel.ID)

204-205: ⚠️ Potential issue

Missing namespace parameter in TestUpdate function call.

The call to NewCreateRuleInput in the update test doesn't include the namespace parameter that was added to the function signature.

Apply this diff to fix the issue:

-	createIn := NewCreateRuleInput("NotificationUpdateRule1", s.channel.ID)
+	createIn := NewCreateRuleInput(s.Env.Namespace(), "NotificationUpdateRule1", s.channel.ID)

241-242: ⚠️ Potential issue

Missing namespace parameter in TestDelete function call.

The call to NewCreateRuleInput in the delete test doesn't include the namespace parameter that was added to the function signature.

Apply this diff to fix the issue:

-	createIn := NewCreateRuleInput("NotificationDeleteRule1", s.channel.ID)
+	createIn := NewCreateRuleInput(s.Env.Namespace(), "NotificationDeleteRule1", s.channel.ID)

258-259: ⚠️ Potential issue

Missing namespace parameter in TestGet function call.

The call to NewCreateRuleInput in the get test doesn't include the namespace parameter that was added to the function signature.

Apply this diff to fix the issue:

-	createIn := NewCreateRuleInput("NotificationGetRule1", s.channel.ID)
+	createIn := NewCreateRuleInput(s.Env.Namespace(), "NotificationGetRule1", s.channel.ID)
♻️ Duplicate comments (1)
openmeter/notification/webhook/svix/webhook.go (1)

434-442: ⚠️ Potential issue

Incorrect ID used for endpoint lookups

The ListWebhooks function is using wh.ID (the user-facing UID) instead of endpointOut.Id (the Svix internal endpoint ID) when looking up secrets and headers. This will likely lead to 404 errors from Svix or wrong secrets being returned.

Apply this fix:

-        wh.Secret, err = h.GetOrUpdateEndpointSecret(ctx, params.Namespace, wh.ID, nil)
+        wh.Secret, err = h.GetOrUpdateEndpointSecret(ctx, params.Namespace, endpointOut.Id, nil)
@@
-        wh.CustomHeaders, err = h.GetOrUpdateEndpointHeaders(ctx, params.Namespace, wh.ID, nil)
+        wh.CustomHeaders, err = h.GetOrUpdateEndpointHeaders(ctx, params.Namespace, endpointOut.Id, nil)

This aligns the ID usage with GetWebhook and CreateWebhook implementations that correctly use the Svix internal endpoint ID.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ef7322 and 75a309f.

📒 Files selected for processing (25)
  • app/common/config.go (1 hunks)
  • app/common/notification.go (2 hunks)
  • app/config/config_test.go (2 hunks)
  • app/config/svix.go (1 hunks)
  • cmd/notification-service/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/notification/consumer/entitlementbalancethreshold.go (1 hunks)
  • openmeter/notification/consumer/entitlementreset.go (1 hunks)
  • openmeter/notification/service/service.go (3 hunks)
  • openmeter/notification/webhook/handler.go (1 hunks)
  • openmeter/notification/webhook/noop.go (0 hunks)
  • openmeter/notification/webhook/noop/noop.go (1 hunks)
  • openmeter/notification/webhook/svix.go (0 hunks)
  • openmeter/notification/webhook/svix/event.go (1 hunks)
  • openmeter/notification/webhook/svix/message.go (1 hunks)
  • openmeter/notification/webhook/svix/svix.go (1 hunks)
  • openmeter/notification/webhook/svix/webhook.go (1 hunks)
  • test/notification/channel.go (6 hunks)
  • test/notification/consumer_balance.go (3 hunks)
  • test/notification/event.go (9 hunks)
  • test/notification/notification_test.go (1 hunks)
  • test/notification/repository.go (1 hunks)
  • test/notification/rule.go (5 hunks)
  • test/notification/testenv.go (9 hunks)
  • test/notification/webhook.go (7 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/notification/webhook/noop.go
  • openmeter/notification/webhook/svix.go
✅ Files skipped from review due to trivial changes (4)
  • app/config/config_test.go
  • app/config/svix.go
  • test/notification/repository.go
  • openmeter/notification/webhook/svix/event.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • app/common/config.go
  • cmd/server/wire_gen.go
  • cmd/notification-service/wire_gen.go
  • openmeter/notification/service/service.go
  • openmeter/notification/webhook/svix/message.go
  • app/common/notification.go
  • openmeter/notification/webhook/noop/noop.go
  • openmeter/notification/webhook/svix/svix.go
🧰 Additional context used
🧠 Learnings (1)
test/notification/testenv.go (1)
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
🧬 Code Graph Analysis (3)
test/notification/channel.go (2)
openmeter/notification/channel.go (1)
  • CreateChannelInput (133-144)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
test/notification/rule.go (5)
openmeter/notification/rule.go (1)
  • CreateRuleInput (147-160)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
test/notification/testenv.go (2)
  • TestMeterSlug (30-30)
  • TestFeatureKey (32-32)
pkg/convert/ptr.go (1)
  • ToPointer (10-12)
test/notification/channel.go (1)
  • NewCreateChannelInput (15-36)
test/notification/webhook.go (2)
openmeter/notification/webhook/handler.go (3)
  • CreateWebhookInput (56-69)
  • UpdateWebhookInput (97-110)
  • ListWebhooksInput (38-44)
pkg/convert/ptr.go (1)
  • ToPointer (10-12)
🔇 Additional comments (50)
openmeter/notification/consumer/entitlementbalancethreshold.go (1)

58-70: Improved error handling approach

The change to collect errors in a slice and join them at the end is a good refactoring that allows all rule processing to continue despite individual failures, providing better error reporting.

test/notification/notification_test.go (1)

14-16: Good test isolation improvement

Switching from a static namespace to a dynamically generated one improves test isolation and prevents potential test interference, which is a good practice.

test/notification/consumer_balance.go (2)

142-143: Improved input parameter handling

Directly passing the namespace to the constructor rather than setting it later improves code clarity and follows the same pattern used in other test files.


461-472: Consistent parameter pattern application

The consistent application of passing namespace directly to constructors maintains a uniform pattern across the test suite, which improves readability and maintainability.

test/notification/channel.go (6)

15-19: Well-executed namespace parameterization.

The function signature update to accept a namespace parameter instead of using a hardcoded value improves test isolation and reusability.


45-45: Properly updated function call to use dynamic namespace.

Consistent update of the function call to pass the test environment's namespace.


59-65: Correctly applies namespace parameterization to list test.

Consistent usage of the dynamic namespace for both test channels, which ensures proper test isolation.


95-95: Properly updated function call in update test.

Consistent use of dynamic namespace in the update test case.


134-134: Properly updated function call in delete test.

Consistent use of dynamic namespace in the delete test case.


150-150: Properly updated function call in get test.

Consistent use of dynamic namespace in the get test case.

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

261-282: Good interface decomposition for improved separation of concerns.

The refactoring of the monolithic Handler interface into three focused interfaces (EventTypeHandler, WebhookHandler, and MessageHandler) and a composite Handler interface is a great improvement. This approach:

  1. Follows the Interface Segregation Principle (SOLID)
  2. Makes it easier to implement partial functionality when needed
  3. Maintains backward compatibility through the composite interface
  4. Facilitates better testing by allowing mock implementations of specific behaviors

This type of interface decomposition will make the codebase more modular and maintainable.

test/notification/rule.go (7)

21-25: Well-executed namespace parameterization for rule inputs.

Similar to the channel.go changes, parameterizing the namespace improves test isolation and reusability.


68-69: Properly updated namespace reference in meter replacement.

Consistent use of the dynamic namespace when replacing meters in the test setup.


90-91: Properly updated namespace reference in meter retrieval.

Consistent use of the dynamic namespace when getting meters by ID or slug.


95-106: Properly updated namespace references in feature management.

Both feature retrieval and creation now use the dynamic namespace.


112-112: Properly updated function call in setup.

Consistent use of dynamic namespace when creating a channel for the test suite.


132-133: Properly updated function call in TestCreate.

Consistent use of dynamic namespace in the create test case.


137-138: Properly updated function call in TestCreate with feature.

Consistent use of dynamic namespace in the create test case with feature configuration.

test/notification/testenv.go (8)

47-53: Good implementation of ULID-based namespace generation.

Adding utility functions for generating unique namespaces using ULIDs is a good approach for test isolation. The helper function correctly uses the test helper marker for better test output.


63-63: Well-designed interface update for namespace access.

Adding the Namespace() method to the TestEnv interface properly exposes the namespace to test cases.


78-78: Proper storage for namespace in test environment.

Adding the namespace field to the testEnv struct is necessary to support the interface method.


107-109: Good implementation of namespace accessor.

The implementation of the Namespace() method simply returns the stored namespace value, which is appropriate.


136-142: Consistent naming from "repo" to "adapter".

Renaming from "repo" to "adapter" is consistent with the terminology change mentioned in the PR summary.


156-163: Well-structured update to use the Svix webhook handler.

The change from the generic webhook handler to the Svix-specific implementation with its dedicated configuration structure aligns with the PR's goal of modularizing webhook handlers.


169-170: Consistent naming from "Repository" to "Adapter".

Updating the field name in the service configuration maintains consistency with the terminology change.


197-203: Properly updated test environment struct initialization.

All field names and values have been correctly updated to match the new structure and naming conventions.

test/notification/event.go (7)

159-159: Function signature update for dynamic namespace handling

The NewCreateEventInput function now accepts a namespace parameter, replacing the previous hardcoded TestNamespace. This change aligns with the broader refactoring effort to use dynamically generated namespaces.


183-184: Consistently using environment-provided namespace

Using s.Env.Namespace() instead of a hardcoded constant improves test isolation and flexibility.


188-188: Consistently using environment-provided namespace

Updated to use dynamic namespace from environment, making the test more maintainable.


198-199: Consistently using environment-provided namespace

The feature creation input correctly uses the dynamic namespace.


209-209: Consistently using environment-provided namespace

Channel creation input now uses the environment's namespace.


217-217: Consistently using environment-provided namespace

Rule creation input now uses the environment's namespace.


229-229: Consistently updated event creation calls

All event creation inputs now consistently use the environment's namespace, ensuring proper test isolation.

Also applies to: 241-241, 260-260, 296-296, 333-333

test/notification/webhook.go (6)

18-18: Function signature update for dynamic namespace handling

The NewCreateWebhookInput function now accepts a namespace parameter instead of using a hardcoded namespace, consistent with the refactoring approach seen in other test files.


25-25: Consistently using environment-provided namespace

Using the passed namespace parameter instead of a hardcoded constant improves test flexibility.


52-52: Consistently updated webhook creation calls

All webhook creation inputs now consistently use the environment's namespace, ensuring proper test isolation.

Also applies to: 74-74, 113-113, 131-131, 157-157, 163-163, 172-172


65-66: Improved array comparison using ElementsMatch

Using assert.ElementsMatch instead of assert.Equal is more appropriate for comparing arrays where the order of elements doesn't matter. This change makes the tests more robust by focusing on content rather than order.


174-175: Updated test channel name

Changed from "test-channel" to "test-channel3" to maintain consistency with test data adjustments.


182-182: Consistently using environment-provided namespace

The list webhooks input now uses the environment's namespace.

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

18-48: Well-structured header management implementation

The GetOrUpdateEndpointHeaders function handles both updating and retrieving custom headers for a webhook endpoint with proper error handling and unwrapping of Svix errors.


50-86: Effective secret management with rotation support

The GetOrUpdateEndpointSecret function correctly retrieves the existing secret and handles rotation when a new secret is provided. The idempotency key generation helps prevent duplicate operations.


88-123: Robust webhook creation with validation and defaults

The first part of the CreateWebhook function includes proper input validation, application creation, and intelligent handling of filter channels to prevent receiving unwanted messages. The automatic secret generation when none is provided is a good usability feature.


124-195: Comprehensive webhook creation implementation

The second part of the CreateWebhook function handles ID generation, endpoint creation with proper configuration, and fetches the necessary secret and custom headers. The use of ULID for ID generation and idempotency keys for request safety are good practices.


197-276: Well-implemented webhook update functionality

The UpdateWebhook function maintains the same robust patterns as CreateWebhook, ensuring namespace application exists, handling empty filters appropriately, and managing secrets and headers properly.


278-333: Efficient channel management implementation

The UpdateWebhookChannels function correctly manages adding and removing channels, maintaining the NullChannel fallback for empty channel lists, and reusing the existing update functionality for consistency.


335-348: Properly implemented webhook deletion

The DeleteWebhook function validates input, deletes the endpoint, and handles errors appropriately.


350-380: Comprehensive webhook retrieval implementation

The GetWebhook function properly validates input, retrieves the endpoint, converts it to a webhook object, and fetches the necessary secret and custom headers.


391-393: Fixed filter to include empty filter cases

The filter function now correctly returns true when no filters are supplied, fixing a previous issue where empty filters would return no results.


444-444: Fixed result handling in ListWebhooks

The function now properly appends the webhook to the results list, addressing a previous issue where results were never appended.


450-464: Well-implemented conversion function

The WebhookFromSvixEndpointOut function correctly maps Svix endpoint fields to webhook fields and filters out the NullChannel from the list of channels.

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

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants