Repository navigation
refactor(notification): webhook handler - #2767
Conversation
📝 WalkthroughWalkthroughThis 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 Changes
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 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (25)
💤 Files with no reviewable changes (2)
🚧 Files skipped from review as they are similar to previous changes (22)
⏰ Context from checks skipped due to timeout of 90000ms (13)
🔇 Additional comments (5)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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.Unmarshalerrors 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
notificationwebhookandsvix. Onlynotificationwebhook.DefaultRegistrationTimeoutis 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 suggestedSolid extraction! Two small follow-ups you may want to consider:
NewNotificationWebhookHandlercurrently decides on the Svix/no-op branch purely viasvixConfig.IsEnabled().
– If the Svix block is taken butwebhooksvix.Newfails (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(...)).- The function returns a concrete instance but does not wrap the error with
errors.WithStackor 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-sitesThe noop implementation is intended for deployments where webhooks are disabled.
Returning a genericfmt.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
📒 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-exportingSvixConfigthrough 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 serviceThe 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 handlerThe 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 initializationSimilar 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 clarityRenaming 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 fieldThe validation check is properly updated to use the renamed field while maintaining the same error message.
63-66: Event handler initialization updated with renamed fieldThe event handler initialization is correctly updated to use the renamed field while maintaining the existing functionality.
76-77: Service struct field assignment updatedThe service struct initialization is properly updated to use the renamed field.
openmeter/notification/webhook/svix/event.go (1)
12-31: Clean and well-structured implementationThe 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 segregationSplitting 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 logicThe 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 packageThe import correctly references the new package location for the Svix webhook implementation.
117-123: Renamed Repository to Adapter for clarityThe 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 packageThe webhook initialization has been correctly updated to use the dedicated Svix implementation.
150-151: Updated service configuration to use Adapter terminologyThe notification service configuration now correctly uses Adapter instead of Repository.
178-179: Updated test environment to use the new adapter variableThe test environment initialization correctly uses the adapter variable instead of repo.
8b77584 to
75a309f
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (4)
test/notification/rule.go (4)
161-167:⚠️ Potential issueMissing namespace parameter in TestList function calls.
The calls to
NewCreateRuleInputin 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 issueMissing namespace parameter in TestUpdate function call.
The call to
NewCreateRuleInputin 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 issueMissing namespace parameter in TestDelete function call.
The call to
NewCreateRuleInputin 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 issueMissing namespace parameter in TestGet function call.
The call to
NewCreateRuleInputin 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 issueIncorrect ID used for endpoint lookups
The
ListWebhooksfunction is usingwh.ID(the user-facing UID) instead ofendpointOut.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
GetWebhookandCreateWebhookimplementations that correctly use the Svix internal endpoint ID.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 approachThe 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 improvementSwitching 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 handlingDirectly 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 applicationThe 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
Handlerinterface into three focused interfaces (EventTypeHandler,WebhookHandler, andMessageHandler) and a compositeHandlerinterface is a great improvement. This approach:
- Follows the Interface Segregation Principle (SOLID)
- Makes it easier to implement partial functionality when needed
- Maintains backward compatibility through the composite interface
- 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 theTestEnvinterface properly exposes the namespace to test cases.
78-78: Proper storage for namespace in test environment.Adding the namespace field to the
testEnvstruct 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 handlingThe
NewCreateEventInputfunction now accepts a namespace parameter, replacing the previous hardcodedTestNamespace. This change aligns with the broader refactoring effort to use dynamically generated namespaces.
183-184: Consistently using environment-provided namespaceUsing
s.Env.Namespace()instead of a hardcoded constant improves test isolation and flexibility.
188-188: Consistently using environment-provided namespaceUpdated to use dynamic namespace from environment, making the test more maintainable.
198-199: Consistently using environment-provided namespaceThe feature creation input correctly uses the dynamic namespace.
209-209: Consistently using environment-provided namespaceChannel creation input now uses the environment's namespace.
217-217: Consistently using environment-provided namespaceRule creation input now uses the environment's namespace.
229-229: Consistently updated event creation callsAll 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 handlingThe
NewCreateWebhookInputfunction 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 namespaceUsing the passed namespace parameter instead of a hardcoded constant improves test flexibility.
52-52: Consistently updated webhook creation callsAll 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 ElementsMatchUsing
assert.ElementsMatchinstead ofassert.Equalis 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 nameChanged from "test-channel" to "test-channel3" to maintain consistency with test data adjustments.
182-182: Consistently using environment-provided namespaceThe list webhooks input now uses the environment's namespace.
openmeter/notification/webhook/svix/webhook.go (11)
18-48: Well-structured header management implementationThe
GetOrUpdateEndpointHeadersfunction 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 supportThe
GetOrUpdateEndpointSecretfunction 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 defaultsThe first part of the
CreateWebhookfunction 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 implementationThe second part of the
CreateWebhookfunction 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 functionalityThe
UpdateWebhookfunction maintains the same robust patterns asCreateWebhook, ensuring namespace application exists, handling empty filters appropriately, and managing secrets and headers properly.
278-333: Efficient channel management implementationThe
UpdateWebhookChannelsfunction 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 deletionThe
DeleteWebhookfunction validates input, deletes the endpoint, and handles errors appropriately.
350-380: Comprehensive webhook retrieval implementationThe
GetWebhookfunction 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 casesThe 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 ListWebhooksThe function now properly appends the webhook to the results list, addressing a previous issue where results were never appended.
450-464: Well-implemented conversion functionThe
WebhookFromSvixEndpointOutfunction correctly maps Svix endpoint fields to webhook fields and filters out the NullChannel from the list of channels.
75a309f to
3181e37
Compare
Overview
Restructure the
webhookpackage of notification service. No change in the business logic.Summary by CodeRabbit
Refactor
Bug Fixes
Chores