Skip to content

feat: subscription sync job - #2492

Merged
turip merged 1 commit into
mainfrom
chore/subscription-sync-job
Mar 20, 2025
Merged

turip merged 1 commit into
mainfrom
chore/subscription-sync-job

Conversation

@turip

@turip turip commented Mar 20, 2025 •

Copy link
Copy Markdown
Member

Overview

This job can be used to resyncronize the state between subscriptions and billing.

Given the flow is fully event driven, a missed/failed event can cause the subscription billing to stop permanently.

This is a safeguard against this possibility.

Summary by CodeRabbit

  • New Features
    • Introduced new subscription synchronization commands for listing and syncing subscriptions with filtering options.
    • Enhanced billing subscription reconciliation to improve invoicing accuracy.
    • Optimized handling of subscription events, ensuring more reliable and consistent billing operations.

@turip
turip requested a review from a team as a code owner March 20, 2025 10:20
@coderabbitai

coderabbitai Bot commented Mar 20, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The pull request introduces new billing subscription functionalities. It adds two functions to create a subscription reconciler and handler, updates the billing command set with a new subscription sync command, and creates a new CLI package for listing and syncing subscriptions. The application wiring is updated to initialize these new components, and a new subscription reconciliation implementation is introduced along with corresponding updates in worker options and event handling.

Changes

File(s) Change Summary
app/common/billing.go Added functions NewBillingSubscriptionReconciler and NewBillingSubscriptionHandler along with a new import for billingworkersubscription.
cmd/jobs/billing/{billing.go,subscriptionsync/sync.go} Added the subscriptionsync.Cmd command to the billing commands and introduced a new package to provide CLI commands (list and all) for subscription synchronization using the cobra library.
cmd/jobs/internal/{wire.go,wire_gen.go} Updated the application wiring: added a BillingSubscriptionReconciler field to the Application struct and revised the initialization process to create the billing subscription handler and reconciler, replacing Kafka producer/metrics.
openmeter/billing/worker/{subscription/reconciler.go,worker.go} Introduced a new Reconciler component with configuration, validation, and methods for listing and reconciling subscriptions, and updated worker options and event handling to use the BillingSubscriptionSyncHandler.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

This job can be used to resyncronize the state between subscriptions
and billing.

Given the flow is fully event driven, a missed/failed event can cause
the subscription billing to stop permanently.

This is a safeguard against this possibility.
@turip
turip force-pushed the chore/subscription-sync-job branch from 85c5041 to 891333e Compare March 20, 2025 10:21

@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

🧹 Nitpick comments (3)
cmd/jobs/billing/subscriptionsync/sync.go (1)

65-67: Duplicate flag definitions across commands.

While functionally correct, the flag definitions are duplicated between the two commands. If you move the flag variables to be scoped to each command as suggested earlier, consider extracting a helper function to define these common flags.

+func addCommonFlags(cmd *cobra.Command, namespaces *[]string, customerIDs *[]string, lookback *time.Duration) {
+	cmd.PersistentFlags().StringSliceVar(namespaces, "n", nil, "filter by namespaces")
+	cmd.PersistentFlags().StringSliceVar(customerIDs, "c", nil, "filter by customer ids")
+	cmd.PersistentFlags().DurationVar(lookback, "l", defaultLookback, "lookback period")
+}

var ListCmd = func() *cobra.Command {
	var (
		namespaces  []string
		customerIDs []string
		lookback    time.Duration
	)
	cmd := &cobra.Command{
		// ...
	}
-	cmd.PersistentFlags().StringSliceVar(&namespaces, "n", nil, "filter by namespaces")
-	cmd.PersistentFlags().StringSliceVar(&customerIDs, "c", nil, "filter by customer ids")
-	cmd.PersistentFlags().DurationVar(&lookback, "l", defaultLookback, "lookback period")
+	addCommonFlags(cmd, &namespaces, &customerIDs, &lookback)
	return cmd
}

Also applies to: 85-87

cmd/jobs/internal/wire_gen.go (1)

323-323: New Subscription Service With Workflow.
Ensures that the entitlement and planService are supplied along with the new validator. The approach is appropriate. Just confirm that new workflow steps are tested if they involve complex subscription state transitions.

Consider reorganizing the arguments to a struct if the param list grows further, for clarity:

- subscriptionServiceWithWorkflow, err := common.NewSubscriptionServices(logger, client, productCatalogConfiguration, entitlementsConfiguration, featureConnector, entitlement, customerService, planService, eventbusPublisher, validator)
+ subscriptionServiceWithWorkflow, err := common.NewSubscriptionServices(common.SubscriptionServicesConfig{
+   Logger: logger,
+   Client: client,
+   ProductCatalogConfig: productCatalogConfiguration,
+   ...
+ })
openmeter/billing/worker/worker.go (1)

139-151: Event Handler now delegates to subscription sync handler.
The methods (HandleSubscriptionCreated, HandleCancelledEvent, SyncronizeSubscription, and HandleInvoiceCreation) are invoked consistently. Ensure correctness of the spelled method name: “SyncronizeSubscription” might be spelled “SynchronizeSubscription” for clarity.

Propose renaming to:

-return w.subscriptionSyncHandler.SyncronizeSubscription(ctx, event.SubscriptionView, time.Now())
+return w.subscriptionSyncHandler.SynchronizeSubscription(ctx, event.SubscriptionView, time.Now())
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a630589 and 891333e.

📒 Files selected for processing (7)
  • app/common/billing.go (2 hunks)
  • cmd/jobs/billing/billing.go (2 hunks)
  • cmd/jobs/billing/subscriptionsync/sync.go (1 hunks)
  • cmd/jobs/internal/wire.go (3 hunks)
  • cmd/jobs/internal/wire_gen.go (8 hunks)
  • openmeter/billing/worker/subscription/reconciler.go (1 hunks)
  • openmeter/billing/worker/worker.go (4 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
cmd/jobs/billing/billing.go (3)
cmd/jobs/billing/subscriptionsync/sync.go (1) (1)
  • Cmd (23-26)
cmd/jobs/billing/advance/advance.go (1) (1)
  • Cmd (14-17)
cmd/jobs/billing/collect/collect.go (1) (1)
  • Cmd (19-22)
cmd/jobs/internal/wire_gen.go (2)
app/common/billing.go (4) (4)
  • BillingSubscriptionValidator (79-84)
  • NewBillingSubscriptionHandler (108-115)
  • NewBillingSubscriptionReconciler (100-106)
  • Billing (26-29)
openmeter/billing/worker/subscription/reconciler.go (1) (1)
  • Reconciler (19-24)
openmeter/billing/worker/subscription/reconciler.go (1)
openmeter/billing/worker/worker.go (1) (1)
  • New (82-124)
cmd/jobs/billing/subscriptionsync/sync.go (2)
cmd/jobs/billing/billing.go (2) (2)
  • init (16-20)
  • Cmd (11-14)
openmeter/billing/worker/subscription/reconciler.go (2) (2)
  • ReconcilerListSubscriptionsInput (61-65)
  • ReconcilerAllInput (101-101)
🔇 Additional comments (34)
cmd/jobs/billing/billing.go (2)

8-8: Clean and necessary import addition.

The import for the new subscriptionsync package is correctly added, maintaining consistency with the existing module imports for the billing package.


19-19: Command integration follows established pattern.

The new subscriptionsync.Cmd is properly integrated alongside the existing billing commands following the same pattern as the advance and collect commands.

cmd/jobs/internal/wire.go (3)

21-21: Clean import for the new subscription worker module.

The import for the billingworkersubscription package is correctly added, following the same naming convention as the other worker-related imports.


39-61: Application struct fields properly formatted.

The restructuring of the fields in the Application struct maintains proper alignment and organization, with the new BillingSubscriptionReconciler field appropriately integrated.


81-82: Wire components for subscription sync properly initialized.

The handlers and reconcilers for subscription synchronization are correctly integrated into the application initialization flow, following the same pattern as the existing components.

cmd/jobs/billing/subscriptionsync/sync.go (2)

37-62: List command implemented correctly.

The implementation properly uses the BillingSubscriptionReconciler.ListSubscriptions method with appropriate error handling and formatted output. The date formatting using RFC3339 is a good choice for consistency and readability.


76-82: All command implementation concise and correct.

The command correctly invokes the BillingSubscriptionReconciler.All method with the appropriate input parameters and error handling.

app/common/billing.go (3)

17-17: Clean import for the subscription worker module.

The import follows the established patterns in the codebase for worker-related imports.


100-106: Subscription reconciler initialization follows established patterns.

The NewBillingSubscriptionReconciler function follows the same pattern as other component initializers in the codebase, providing the appropriate dependencies to the reconciler.


108-115: Subscription handler initialization is well-structured.

The NewBillingSubscriptionHandler function properly initializes the subscription handler with the required services and follows the established patterns in the codebase.

cmd/jobs/internal/wire_gen.go (9)

19-19: Import of subscription worker package looks good.
No specific concerns. This import is necessary for creating the new billing subscription reconciler.


313-313: Validator object creation is correct.
Instantiates BillingSubscriptionValidator with the billing service and config. Validate that the validator is leveraged properly in the subsequent subscription calls.


333-333: Instantiating subscription handler succeeds.
Provides a dedicated billing subscription handler for the new workflow. This is straightforward.


343-352: Introduces a new reconciler for billing subscriptions.
Creation logic plus cleanup steps are consistent with the existing pattern. No issues found.


353-362: Kafka producer creation re-ordered here.
The code injects the new subscription reconciler before spinning up the producer, maintaining a topological initialization flow. Looks fine.


363-363: Creating Kafka metrics after the producer.
Ensures the metrics object is initialized using the final meter instance. The ordering is appropriate.


374-399: Composing the Application structure with new billing subscription components.
The changes properly set up the new BillingSubscriptionReconciler and associated services in the returned Application. The ordering is consistent with the rest of the code.


416-438: Added fields in the Application struct to accommodate new subscription synchronization logic.
All newly introduced fields are consistent with the prior initialization. The naming and referencing appear coherent.


302-303:

Details

✅ Verification successful

Initialize Plan Service for product catalog configuration.
Everything appears correct; it fetches the product catalog config and initializes the plan service. Just ensure that any usage of planService is updated to accommodate your new subscription logic if required.

Please confirm that other parts of the codebase use the newly created Plan Service as intended (e.g., references to older plan service objects have been removed or renamed).


🏁 Script executed:

#!/bin/bash
# Searching references to any older plan service usage
rg -A 3 -B 3 'PlanService(.*)'

Length of output: 26395


Validated: Consistent Plan Service usage across the codebase.
The grep results confirm that all references to the Plan Service—including in production files (e.g., in all wire_gen.go files) and test suites—are correctly using the new service instance from common.NewPlanService. There are no outdated references; integration points have been updated to align with the new subscription logic.

openmeter/billing/worker/worker.go (4)

28-30: New fields for billing subscription sync.
This extends WorkerOptions to include a new Subscription Sync Handler. Good injection approach.


65-68: Validation for BillingSubscriptionSyncHandler.
Enforces that BillingSubscriptionSyncHandler is non-nil, ensuring the worker cannot run without subscription sync logic.


75-77: Renamed struct fields to reflect the new subscription sync handler.
This improves clarity, differentiating the sync handler from other billing handlers.


97-99: Worker initialization with sync handler and async advancer.
This assignment is consistent with other fields in the worker. No issues found.

openmeter/billing/worker/subscription/reconciler.go (11)

1-2: New package and file introduced for billing subscription reconciliation.
No immediate concerns.


3-14: Imports reflect dependencies for logging, time, and subscription services.
All look appropriate.


16-24: Reconciler struct definition.
Stores references to the subscription sync handler, the subscription service, and a logger. This separation of concerns is concise and clear.


26-31: ReconcilerConfig struct.
Encapsulates essential dependencies needed by the Reconciler. Great usage of explicit config struct.


33-47: Validation method ensures ReconcilerConfig is correct.
Prevents runtime errors by requiring subscription sync handler, subscription service, and logger.


49-59: NewReconciler constructor with config validation.
Immediately checks config validity before constructing the Reconciler. Implementation is straightforward. Watch out for any advanced concurrency aspects if expansions occur.


61-65: ReconcilerListSubscriptionsInput struct.
Holds filtering and time-based constraints for listing subscriptions. Nicely grouped.


67-73: Validation of lookback > 0.
This check prevents invalid usage.


75-90: ListSubscriptions method obtains active subscriptions in a given timeframe.
The usage of lo.ToPtr(...) for the active time with lookback is a neat approach. Properly wraps errors with context.


101-119: All method iterates over fetched subscriptions, logs errors, and aggregates them.

  • Combined errors via errors.Join is a good approach if using Go ≥ 1.20.
  • Each subscription is treated individually, with failures logged but not halting the entire run.

92-99:

Details

❓ Verification inconclusive

ReconcileSubscription fetches subscription view, calls the sync.
Implementation is straightforward. Consider verifying that the SyncronizeSubscription method can handle all subscription states.

Please confirm the presence of integration tests that cover all subscription states. Example script:


🏁 Script executed:

#!/bin/bash
rg -A 5 'SyncronizeSubscription' test/

Length of output: 279


Action: Verify integration tests fully cover all subscription states

The integration tests in test/billing/subscription_test.go already invoke SyncronizeSubscription (see the test call on line 1 of the snippet). However, it's still unclear if these tests cover all possible subscription states (including edge cases and error scenarios). Please double-check and expand the tests if needed to ensure comprehensive coverage for all subscription states.

Comment on lines +17 to +21
var (
namespaces []string
customerIDs []string
lookback time.Duration
)

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.

🛠️ Refactor suggestion

Avoid package-level flag variables.

These flag variables are defined at the package level and shared between both subcommands. This can lead to unexpected behavior if multiple commands are executed in sequence within the same process.

Consider scoping these variables to each command function instead:

-var (
-	namespaces  []string
-	customerIDs []string
-	lookback    time.Duration
-)

var ListCmd = func() *cobra.Command {
+	var (
+		namespaces  []string
+		customerIDs []string
+		lookback    time.Duration
+	)
	cmd := &cobra.Command{
		// ...
	}
	// ...
}

var AllCmd = func() *cobra.Command {
+	var (
+		namespaces  []string
+		customerIDs []string
+		lookback    time.Duration
+	)
	cmd := &cobra.Command{
		// ...
	}
	// ...
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var (
namespaces []string
customerIDs []string
lookback time.Duration
)
// Removed package-level flag variables
// var (
// namespaces []string
// customerIDs []string
// lookback time.Duration
// )
var ListCmd = func() *cobra.Command {
// Scoped flag variables for ListCmd
var (
namespaces []string
customerIDs []string
lookback time.Duration
)
cmd := &cobra.Command{
// ...
}
// ...
return cmd
}
var AllCmd = func() *cobra.Command {
// Scoped flag variables for AllCmd
var (
namespaces []string
customerIDs []string
lookback time.Duration
)
cmd := &cobra.Command{
// ...
}
// ...
return cmd
}

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

🧹 Nitpick comments (8)
cmd/jobs/billing/subscriptionsync/sync.go (3)

17-21: Consider scoping flag variables to command functions.

The flag variables (namespaces, customerIDs, lookback) are currently defined at the package level. This could cause unexpected behavior if commands are executed sequentially, as they would share these variables.

Consider scoping these variables within each command function:

-var (
-	namespaces  []string
-	customerIDs []string
-	lookback    time.Duration
-)

var ListCmd = func() *cobra.Command {
+	var (
+		namespaces  []string
+		customerIDs []string
+		lookback    time.Duration
+	)
	cmd := &cobra.Command{
		// ...
	}
	// ...
}

var AllCmd = func() *cobra.Command {
+	var (
+		namespaces  []string
+		customerIDs []string
+		lookback    time.Duration
+	)
	cmd := &cobra.Command{
		// ...
	}
	// ...
}

33-70: Consider adding pagination for the list command.

The list command currently doesn't have any provisions for pagination or limiting the number of results, which could be problematic if there are a large number of subscriptions.

Consider adding pagination flags and handling:

var ListCmd = func() *cobra.Command {
	var (
		namespaces  []string
		customerIDs []string
		lookback    time.Duration
+		limit       int
+		offset      int
	)
	cmd := &cobra.Command{
		// ...
		RunE: func(cmd *cobra.Command, args []string) error {
			// ...
+			// Apply pagination
+			start := offset
+			end := offset + limit
+			if end > len(subs) {
+				end = len(subs)
+			}
+			if start > len(subs) {
+				start = len(subs)
+			}
+			subs = subs[start:end]
			
			for _, sub := range subs {
				// ...
			}
+			fmt.Printf("Showing %d-%d of %d subscriptions\n", start+1, end, len(subs))
			return nil
		},
	}
	
	// ...
+	cmd.PersistentFlags().IntVar(&limit, "limit", 50, "maximum number of results to return")
+	cmd.PersistentFlags().IntVar(&offset, "offset", 0, "number of results to skip")
	
	return cmd
}

72-89: Consider refactoring common flag setup to reduce duplication.

The flag setup is duplicated between ListCmd and AllCmd. Consider extracting a common function to set up these flags to improve maintainability.

You could create a helper function to add the common flags:

+func addCommonFlags(cmd *cobra.Command, namespaces *[]string, customerIDs *[]string, lookback *time.Duration) {
+	cmd.PersistentFlags().StringSliceVar(namespaces, "n", nil, "filter by namespaces")
+	cmd.PersistentFlags().StringSliceVar(customerIDs, "c", nil, "filter by customer ids")
+	cmd.PersistentFlags().DurationVar(lookback, "l", defaultLookback, "lookback period")
+}

var ListCmd = func() *cobra.Command {
	var (
		namespaces  []string
		customerIDs []string
		lookback    time.Duration
	)
	cmd := &cobra.Command{
		// ...
	}
-	cmd.PersistentFlags().StringSliceVar(&namespaces, "n", nil, "filter by namespaces")
-	cmd.PersistentFlags().StringSliceVar(&customerIDs, "c", nil, "filter by customer ids")
-	cmd.PersistentFlags().DurationVar(&lookback, "l", defaultLookback, "lookback period")
+	addCommonFlags(cmd, &namespaces, &customerIDs, &lookback)
	return cmd
}

var AllCmd = func() *cobra.Command {
	var (
		namespaces  []string
		customerIDs []string
		lookback    time.Duration
	)
	cmd := &cobra.Command{
		// ...
	}
-	cmd.PersistentFlags().StringSliceVar(&namespaces, "n", nil, "filter by namespaces")
-	cmd.PersistentFlags().StringSliceVar(&customerIDs, "c", nil, "filter by customer ids")
-	cmd.PersistentFlags().DurationVar(&lookback, "l", defaultLookback, "lookback period")
+	addCommonFlags(cmd, &namespaces, &customerIDs, &lookback)
	return cmd
}
openmeter/billing/worker/worker.go (2)

75-77: Introduce subscriptionSyncHandler within the Worker struct.
The addition of subscriptionSyncHandler aligns with the new subscription synchronization approach. Ensuring consistent naming across the codebase (e.g., "Sync" vs. "Synchronize") improves clarity.


139-139: *Use subscriptionSyncHandler methods to process subscription-related events.
Each of these lines routes a different subscription event (create, cancel, update, etc.) to the subscription sync handler. Be mindful of possible spelling inconsistencies like "SyncronizeSubscription." Consider writing it as "SynchronizeSubscription" for clarity and uniformity.

Also applies to: 142-142, 145-145, 148-148, 151-151

cmd/jobs/internal/wire_gen.go (1)

302-399: Configure new billing subscription services and handlers.
These lines introduce:

  • Product catalog configuration handling.
  • A new subscription validator, subscription workflow service, subscription handler, and subscription reconciler.
  • Kafka producer and metrics instantiation.

All of these additions outline a comprehensive setup for subscription-based billing flows, improving the resiliency of billing operations. Ensure thorough testing of each component’s integration.

openmeter/billing/worker/subscription/reconciler.go (2)

92-99: ReconcileSubscription fetches subscription view and syncs.
The logic is straightforward: fetch the subscription, then pass the subscription view to SyncronizeSubscription. Consider adopting a consistent spelling "SynchronizeSubscription" for uniform readability.


101-119: All method: Reconcile all relevant subscriptions.
Iterating over subscriptions and accumulating errors is practical for batch processing. Logging each failed reconciliation provides transparency. Returning a joined error is helpful, but consider more granular error reporting to enhance debugging if the list is large.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a630589 and 891333e.

📒 Files selected for processing (7)
  • app/common/billing.go (2 hunks)
  • cmd/jobs/billing/billing.go (2 hunks)
  • cmd/jobs/billing/subscriptionsync/sync.go (1 hunks)
  • cmd/jobs/internal/wire.go (3 hunks)
  • cmd/jobs/internal/wire_gen.go (8 hunks)
  • openmeter/billing/worker/subscription/reconciler.go (1 hunks)
  • openmeter/billing/worker/worker.go (4 hunks)
🧰 Additional context used
🧬 Code Definitions (7)
cmd/jobs/billing/billing.go (1)
cmd/jobs/billing/subscriptionsync/sync.go (1) (1)
  • Cmd (23-26)
cmd/jobs/internal/wire.go (2)
app/common/billing.go (2) (2)
  • Billing (26-29)
  • NewBillingSubscriptionReconciler (100-106)
openmeter/billing/worker/subscription/reconciler.go (1) (1)
  • Reconciler (19-24)
app/common/billing.go (3)
app/common/subscription.go (1) (1)
  • SubscriptionServiceWithWorkflow (33-37)
openmeter/billing/worker/subscription/sync.go (3) (3)
  • Handler (61-67)
  • New (69-80)
  • Config (33-39)
openmeter/billing/worker/subscription/reconciler.go (3) (3)
  • Reconciler (19-24)
  • NewReconciler (49-59)
  • ReconcilerConfig (26-31)
cmd/jobs/billing/subscriptionsync/sync.go (2)
cmd/jobs/billing/billing.go (2) (2)
  • init (16-20)
  • Cmd (11-14)
openmeter/billing/worker/subscription/reconciler.go (2) (2)
  • ReconcilerListSubscriptionsInput (61-65)
  • ReconcilerAllInput (101-101)
cmd/jobs/internal/wire_gen.go (3)
app/common/billing.go (3) (3)
  • NewBillingSubscriptionHandler (108-115)
  • NewBillingSubscriptionReconciler (100-106)
  • Billing (26-29)
cmd/jobs/internal/wire.go (1) (1)
  • Application (35-62)
openmeter/billing/worker/subscription/reconciler.go (1) (1)
  • Reconciler (19-24)
openmeter/billing/worker/worker.go (5)
openmeter/billing/service.go (1) (1)
  • Service (9-19)
openmeter/billing/service/service.go (1) (1)
  • Service (23-37)
openmeter/billing/worker/subscription/sync.go (1) (1)
  • Handler (61-67)
openmeter/billing/worker/asyncadvance/asyncadvance.go (1) (1)
  • Handler (11-14)
openmeter/billing/events.go (2) (2)
  • InvoiceCreatedEvent (27-29)
  • EventInvoice (13-13)
openmeter/billing/worker/subscription/reconciler.go (1)
openmeter/billing/worker/worker.go (1) (1)
  • New (82-124)
🔇 Additional comments (19)
cmd/jobs/billing/billing.go (2)

8-8: Clean import addition for the new subscriptionsync module.

The import for the subscriptionsync module is properly added to the imports block.


19-19: Command properly integrated into the billing command structure.

The subscriptionsync command is correctly added to the billing command hierarchy, enabling the new subscription synchronization functionality to be accessible through the CLI.

cmd/jobs/internal/wire.go (3)

21-21: Clean import addition for the subscription reconciliation module.

The import for the billingworkersubscription package is properly added to the imports block, maintaining alphabetical ordering.


39-62: Application struct field properly added for subscription reconciliation.

The BillingSubscriptionReconciler field is correctly added to the Application struct, maintaining consistent field alignment and naming patterns.


81-82: Proper wiring of new subscription reconciliation components.

The new billing subscription handler and reconciler initialization functions are correctly added to the application wiring, enabling the subscription synchronization functionality.

cmd/jobs/billing/subscriptionsync/sync.go (1)

23-26: Main command structure looks good.

The main command is properly defined with appropriate use and description.

app/common/billing.go (3)

17-17: Clean import addition for the subscription worker module.

The import for the billingworkersubscription package is properly added to the imports block.


100-106: Well-structured reconciler initialization function.

The NewBillingSubscriptionReconciler function follows the established pattern in the codebase for component initialization, properly passing the required dependencies to the reconciler.


108-115: Well-structured handler initialization function.

The NewBillingSubscriptionHandler function is correctly implemented, providing the necessary dependencies for the subscription handler, including subscription service, billing service, transaction creator, and logger.

openmeter/billing/worker/worker.go (3)

28-30: Add new fields to WorkerOptions for billing and subscription handling.
These fields (BillingAdapter, BillingService, BillingSubscriptionSyncHandler) are necessary for the new subscription synchronization logic. The naming is consistent, and including them here centralizes the dependencies for better maintainability.


65-67: Validate the BillingSubscriptionSyncHandler to avoid nil references.
Requiring BillingSubscriptionSyncHandler at runtime is crucial for preventing panics when subscription events are processed. This is a good defensive programming technique.


98-99: Inject BillingService and subscriptionSyncHandler into Worker.
Populating billingService and subscriptionSyncHandler from opts is consistent with the WorkerOptions. This maintains a single source of truth and improves cohesion within the Worker lifecycle.

cmd/jobs/internal/wire_gen.go (2)

19-19: Add subscription package import.
Importing the subscription worker package is necessary to create and configure the subscription sync logic.


416-439: Expand Application struct to include subscription and billing fields.
Adding fields like BillingSubscriptionReconciler and SubscriptionServiceWithWorkflow ensures the application can fully manage subscription synchronization. Carefully maintain these references in the rest of the code to keep initialization paths orderly.

openmeter/billing/worker/subscription/reconciler.go (5)

16-24: Introduce Reconciler to manage subscription state reconciliation.
The Reconciler struct holds both the subscription sync handler and subscription service references. This design promotes clear delineation of responsibilities and fosters modular subscription management.


26-47: ReconcilerConfig: Validate required dependencies.
The ReconcilerConfig ensures that no required fields (SubscriptionSync, SubscriptionService, Logger) are nil, avoiding runtime errors. This explicit check is a good defensive strategy.


49-59: NewReconciler constructor enforces config validation.
The constructor pattern ensures a properly initialized Reconciler, preventing the introduction of partial or incorrect states. This approach is aligned with idiomatic Go factory functions.


61-73: ReconcilerListSubscriptionsInput: Validate lookback duration.
Requiring a positive Lookback avoids logical errors, such as querying times in the future. This constraint eliminates user misconfiguration and ensures consistent data retrieval.


75-90: ListSubscriptions method relies on subscription service list.
The method ensures validity checks on the input and provides a stable approach to retrieving subscriptions for reconciliation. Implement thorough tests to validate boundary conditions and confirm that only relevant subscriptions are returned.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants