Skip to content

feat: add adapter for planaddon service - #2675

Merged
chrisgacsal merged 5 commits into
mainfrom
feat/productcatalog
Apr 16, 2025
Merged

chrisgacsal merged 5 commits into
mainfrom
feat/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Apr 16, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Add adapter implementation for plan add-on assignment service which includes common types and the adapter itself.

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive support for managing plan add-ons, including creation, retrieval, updating, listing, and deletion.
    • Added event types and error handling specific to plan add-on lifecycle events.
    • Enhanced validation and conversion for plan add-on entities.
    • Added a new method to convert plans without filtering deleted phases.
    • Implemented a transactional repository adapter for plan add-ons with integrated logging.
    • Provided a structured service interface with robust input validation and flexible filtering for plan add-ons.
  • Bug Fixes

    • Improved error messages and validation checks for plan add-on assignments.
    • Enhanced validation to verify phase keys and rate card compatibility in plan add-ons.
  • Tests

    • Added extensive integration and unit tests for plan add-on functionality, including lifecycle operations.
    • Introduced test utilities for creating consistent test data for plans, add-ons, features, meters, and namespaces.
    • Provided assertion helpers to facilitate plan add-on test validations.
  • Documentation

    • Updated and clarified error messages and event metadata for better traceability.
  • Refactor

    • Refactored plan add-on assignment structures for improved metadata handling and validation logic.
    • Improved internal logging and error handling in adapters and test environments.
    • Replaced discard logger implementation with a full interface-compliant handler.

@coderabbitai

coderabbitai Bot commented Apr 16, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change introduces a comprehensive implementation for managing "PlanAddon" entities within the product catalog system. It adds a new planaddon package, defining core domain models, validation, conversion methods, service and repository interfaces, error handling, and event types for plan add-on assignments. The implementation includes a Postgres-backed adapter with full CRUD operations, transactional support, and eager loading of related entities. Extensive test utilities and integration tests are provided to validate the functionality, including helpers for generating test data and environments. Existing plan and plan adapter code is updated for compatibility, and a new discard logger implementation is introduced for testing purposes.

Changes

File(s) Change Summary
openmeter/productcatalog/planaddon/planaddon.go Defines the PlanAddon struct embedding IDs, metadata, plan, and addon fields. Implements validation and conversion to product catalog representation.
openmeter/productcatalog/planaddon/service.go Adds the Service interface for plan add-ons, input types for CRUD operations, validation logic, and ordering constants.
openmeter/productcatalog/planaddon/repository.go Defines the Repository interface with transactional support and CRUD methods for plan addons.
openmeter/productcatalog/planaddon/adapter/adapter.go Implements the Postgres-backed adapter for plan addons: configuration, transaction management, and repository instantiation.
openmeter/productcatalog/planaddon/adapter/planaddon.go Implements CRUD operations for plan addons, including listing with filtering, creation, retrieval, update, and soft deletion with eager loading.
openmeter/productcatalog/planaddon/adapter/mapping.go Adds function to map database rows to domain PlanAddon models, including validation and conversion of related plan and addon entities.
openmeter/productcatalog/planaddon/adapter/adapter_test.go Adds comprehensive integration tests for the plan addon adapter covering full lifecycle and CRUD operations.
openmeter/productcatalog/planaddon/assert.go Adds test helper functions for asserting equality between plan addon inputs and models.
openmeter/productcatalog/planaddon/errors.go Introduces typed not-found error for plan addons with parameterized context and helper functions for error identification.
openmeter/productcatalog/planaddon/errors_test.go Adds unit tests for plan addon not-found error handling and error message formatting.
openmeter/productcatalog/planaddon/event.go Defines event types and constructors for plan addon creation, update, and deletion, including validation and metadata generation.
openmeter/productcatalog/planaddon/planaddon.go Refactors plan addon assignment struct to new PlanAddon model with embedded metadata/config, updates validation to use phase keys, and improves error messages.
openmeter/productcatalog/plan/adapter/mapping.go Renames function fromPlanRow to exported FromPlanRow for cross-package usage.
openmeter/productcatalog/plan/adapter/plan.go Updates calls from fromPlanRow to FromPlanRow for plan entity mapping.
openmeter/productcatalog/plan/plan.go Adds AsProductCatalogPlan2 method converting plan to product catalog format without filtering or error handling.
openmeter/productcatalog/planaddon/testutils/addon.go Adds test utility function to generate default CreateAddonInput structs for testing.
openmeter/productcatalog/planaddon/testutils/env.go Adds reusable test environment struct and setup/teardown logic for plan addon integration tests.
openmeter/productcatalog/planaddon/testutils/feature.go Adds helper functions for generating test feature inputs, including variants based on meters.
openmeter/productcatalog/planaddon/testutils/meters.go Adds helper function generating a set of test meter definitions for use in tests.
openmeter/productcatalog/planaddon/testutils/namespace.go Adds helper for generating ULID-based namespaces for tests and aliases it for convenience.
openmeter/productcatalog/planaddon/testutils/plan.go Adds helper function to generate default CreatePlanInput structs for plan tests.
openmeter/testutils/logger.go Replaces discard logger handler with a full implementation of the slog.Handler interface for improved test logging suppression.

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

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 ecd388b and 5225020.

📒 Files selected for processing (5)
  • openmeter/productcatalog/planaddon.go (2 hunks)
  • openmeter/productcatalog/planaddon/adapter/adapter_test.go (1 hunks)
  • openmeter/productcatalog/planaddon/adapter/mapping.go (1 hunks)
  • openmeter/productcatalog/planaddon/assert.go (1 hunks)
  • openmeter/productcatalog/planaddon/event.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • openmeter/productcatalog/planaddon/adapter/mapping.go
  • openmeter/productcatalog/planaddon/adapter/adapter_test.go
  • openmeter/productcatalog/planaddon.go
  • openmeter/productcatalog/planaddon/assert.go
  • openmeter/productcatalog/planaddon/event.go
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • 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)

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

@chrisgacsal
chrisgacsal force-pushed the feat/productcatalog branch from 83b343a to 3ec0df9 Compare April 16, 2025 09:02
@chrisgacsal
chrisgacsal force-pushed the feat/productcatalog branch from 3ec0df9 to bd1fd5d Compare April 16, 2025 09:26
@chrisgacsal chrisgacsal added the release-note/feature Release note: Exciting New Features label Apr 16, 2025
@chrisgacsal chrisgacsal self-assigned this Apr 16, 2025
@chrisgacsal chrisgacsal changed the title feat: add plan add-on assignment service feat: add adapter for planaddon service Apr 16, 2025
@chrisgacsal
chrisgacsal marked this pull request as ready for review April 16, 2025 09:31
@chrisgacsal
chrisgacsal requested a review from a team as a code owner April 16, 2025 09:31
tothandras
tothandras previously approved these changes Apr 16, 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: 8

🧹 Nitpick comments (18)
openmeter/productcatalog/plan/plan.go (1)

60-65: Good addition of a simplified conversion method

This new AsProductCatalogPlan2 method provides a convenient way to convert a Plan to a productcatalog.Plan without filtering phases by time. This is useful for scenarios where you need the raw plan data without any filtering.

Consider adding a brief comment explaining the difference between this method and AsProductCatalogPlan, especially why this doesn't filter deleted resources or return an error.

+// AsProductCatalogPlan2 converts a Plan to a productcatalog.Plan without filtering deleted resources
+// or returning an error, unlike AsProductCatalogPlan which filters by time.
 func (p Plan) AsProductCatalogPlan2() productcatalog.Plan {
     return productcatalog.Plan{
         PlanMeta: p.PlanMeta,
         Phases:   lo.Map(p.Phases, func(phase Phase, _ int) productcatalog.Phase { return phase.AsProductCatalogPhase() }),
     }
 }
openmeter/productcatalog/planaddon/testutils/meters.go (2)

13-81: Consider adding more distinguishable names to the test meters.

While the implementation is solid, all three meters have the same name "Test meter" which might make it difficult to distinguish between them in test logs or when debugging. Consider giving each meter a unique descriptive name that reflects its purpose or configuration.

-				Name: "Test meter",
+				Name: "API Requests Meter",
-				Name: "Test meter",
+				Name: "Tokens Total Meter",
-				Name: "Test meter",
+				Name: "Workload Runtime Meter",

24-25: Consider using fixed timestamps for improved test determinism.

Using time.Now() for timestamps in tests can lead to non-deterministic behavior when tests depend on these timestamps. For better test determinism, consider using fixed timestamps or a time provider that can be controlled in tests.

-					CreatedAt: time.Now(),
-					UpdatedAt: time.Now(),
+					CreatedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
+					UpdatedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),

Also applies to: 44-45, 65-66

openmeter/productcatalog/planaddon/errors_test.go (1)

48-85: Consider removing debug logging in the test.

The implementation tests the string representation thoroughly with different parameter combinations. However, there's a debug log statement on line 80 (t.Logf("%v", test.Error)) that may be left over from development. Consider removing it as it adds noise to the test output.

-			t.Logf("%v", test.Error)
openmeter/productcatalog/planaddon/adapter/adapter_test.go (3)

25-26: Consider documenting the purpose of MonthPeriod variable.

This variable represents a month period for testing purposes, but its meaning and usage could be more explicit with a comment.

-var MonthPeriod = isodate.FromDuration(30 * 24 * time.Hour)
+// MonthPeriod represents a standardized 30-day month duration for testing billing periods
+var MonthPeriod = isodate.FromDuration(30 * 24 * time.Hour)

73-76: Repository initialization could be moved to the test environment.

The adapter initialization could be extracted to the test environment setup to ensure consistent initialization across tests.

Consider moving the repository initialization to the planaddontestutils.NewTestEnv function for reusability.


88-231: Consider extracting plan phase setup to a helper function.

The test contains a large amount of setup code for plan phases. This could be extracted to improve readability.

// Create a helper function in testutils package
+func NewTestPlanWithPhases(t *testing.T, namespace string, feature feature.Feature) plan.CreatePlanInput {
+    planInput := NewTestPlan(t, namespace)
+    planInput.Phases = []productcatalog.Phase{
+        // Phase definitions as in the test...
+    }
+    return planInput
+}

// In the test:
-planV1Input.Phases = []productcatalog.Phase{
-    // ... many lines of phase setup
-}
+planV1Input = planaddontestutils.NewTestPlanWithPhases(t, namespace, feature1)
openmeter/productcatalog/planaddon/errors.go (2)

12-18: Add documentation comments to the error type.

The NotFoundErrorParams struct lacks documentation comments explaining its purpose and usage.

+// NotFoundErrorParams contains the identifying information for a not found plan add-on.
+// At least one of the fields should be provided to create a meaningful error message.
 type NotFoundErrorParams struct {
+	// Namespace is the tenant namespace
 	Namespace    string
+	// ID is the unique identifier of the plan add-on
 	ID           string
+	// PlanIDOrKey is either the ID or key of the associated plan
 	PlanIDOrKey  string
+	// AddonIDOrKey is either the ID or key of the associated add-on
 	AddonIDOrKey string
 }

19-49: Consider simplifying the error message construction.

The current approach builds the error message through multiple string concatenations and conditionals. A map or slice-based approach might be cleaner.

 func NewNotFoundError(e NotFoundErrorParams) *NotFoundError {
-	var m string
-
-	if e.Namespace != "" {
-		m += fmt.Sprintf(" namespace=%s", e.Namespace)
-	}
-
-	if e.ID != "" {
-		m += fmt.Sprintf(" id=%s", e.ID)
-	}
-
-	if e.PlanIDOrKey != "" {
-		m += fmt.Sprintf(" plan.idOrKey=%s", e.PlanIDOrKey)
-	}
-
-	if e.AddonIDOrKey != "" {
-		m += fmt.Sprintf(" addon.idOrKey=%s", e.AddonIDOrKey)
-	}
-
-	if len(m) > 0 {
-		m = fmt.Sprintf("plan add-on assignment not found [%s]", m[1:])
-	} else {
-		m = "plan add-on assignment not found"
-	}
+	parts := []string{}
+	if e.Namespace != "" {
+		parts = append(parts, fmt.Sprintf("namespace=%s", e.Namespace))
+	}
+	if e.ID != "" {
+		parts = append(parts, fmt.Sprintf("id=%s", e.ID))
+	}
+	if e.PlanIDOrKey != "" {
+		parts = append(parts, fmt.Sprintf("plan.idOrKey=%s", e.PlanIDOrKey))
+	}
+	if e.AddonIDOrKey != "" {
+		parts = append(parts, fmt.Sprintf("addon.idOrKey=%s", e.AddonIDOrKey))
+	}
+
+	msg := "plan add-on assignment not found"
+	if len(parts) > 0 {
+		msg = fmt.Sprintf("%s [%s]", msg, strings.Join(parts, " "))
+	}

 	return &NotFoundError{
 		err: models.NewGenericNotFoundError(
-			errors.New(m),
+			errors.New(msg),
 		),
 	}
 }

Note: Don't forget to import strings package if you implement this suggestion.

openmeter/productcatalog/planaddon.go (2)

17-23: Add documentation for PlanAddonConfig fields.

The fields in PlanAddonConfig lack detailed documentation explaining their purpose and constraints.

 type PlanAddonConfig struct {
-	// FromPlanPhase
+	// FromPlanPhase specifies the plan phase from which this add-on will be available.
+	// The add-on will be available in this phase and all subsequent phases.
 	FromPlanPhase string `json:"fromPlanPhase"`

-	// MaxQuantity
+	// MaxQuantity defines the maximum number of instances allowed for this add-on.
+	// This is only applicable for add-ons with InstanceTypeMultiple.
+	// If nil, there is no limit to the number of instances.
 	MaxQuantity *int `json:"maxQuantity"`
 }

94-118: Consider using a map for phase lookup.

The current implementation searches for a phase by key using a linear scan, which could be inefficient for plans with many phases.

 if len(c.Plan.Phases) > 0 {
-	var phaseIdx = -1
-	for i, phase := range c.Plan.Phases {
-		if phase.Key == c.FromPlanPhase {
-			phaseIdx = i
-			break
-		}
-	}
-
-	if phaseIdx == -1 {
+	// Create a map of phase keys to indices for more efficient lookup
+	phaseIndices := make(map[string]int, len(c.Plan.Phases))
+	for i, phase := range c.Plan.Phases {
+		phaseIndices[phase.Key] = i
+	}
+
+	if phaseIdx, ok := phaseIndices[c.FromPlanPhase]; !ok {
 		errs = append(errs, fmt.Errorf("plan does not have phase %q", c.FromPlanPhase))
 	} else {
 		// Validate ratecards from plan phases and addon.
openmeter/productcatalog/planaddon/assert.go (1)

59-67: Consider expanding AssertPlanAddonEqual.

The AssertPlanAddonEqual function only checks a subset of fields. Consider adding more checks for Plan, Addon, and MaxQuantity fields.

 func AssertPlanAddonEqual(t *testing.T, expected, actual PlanAddon) {
 	t.Helper()

 	assert.Equalf(t, expected.ID, actual.ID, "id mismatch")
 	assert.Equalf(t, expected.FromPlanPhase, actual.FromPlanPhase, "plan phase key mismatch")
 	assert.Equalf(t, expected.Metadata, actual.Metadata, "metadata mismatch")
 	assert.Equalf(t, expected.Annotations, actual.Annotations, "annotations mismatch")
+	
+	// Check Plan fields
+	assert.Equalf(t, expected.Plan.ID, actual.Plan.ID, "plan id mismatch")
+	assert.Equalf(t, expected.Plan.Key, actual.Plan.Key, "plan key mismatch")
+	
+	// Check Addon fields
+	assert.Equalf(t, expected.Addon.ID, actual.Addon.ID, "add-on id mismatch")
+	assert.Equalf(t, expected.Addon.Key, actual.Addon.Key, "add-on key mismatch")
+	
+	// Check MaxQuantity
+	if expected.MaxQuantity == nil {
+		assert.Nilf(t, actual.MaxQuantity, "max quantity should be nil")
+	} else {
+		assert.NotNilf(t, actual.MaxQuantity, "max quantity should not be nil")
+		assert.Equalf(t, *expected.MaxQuantity, *actual.MaxQuantity, "max quantity mismatch")
+	}
 }
openmeter/productcatalog/planaddon/planaddon.go (1)

20-21: Correct the comment for the Plan field.

Lines 20-21 contain a mismatched comment. It still reads “// Addon” though the field is actually named Plan. Consider updating the comment to reflect the field’s purpose.

  // Addon
- Plan plan.Plan `json:"plan"`
+ // Plan
+ Plan plan.Plan `json:"plan"`
openmeter/productcatalog/planaddon/service.go (3)

82-84: Consider adding validation for ListPlanAddonsInput

The Validate() method currently returns nil without performing any validation checks. Consider validating that the Order and OrderBy fields contain valid values to prevent potential runtime errors.

func (i ListPlanAddonsInput) Validate() error {
-	return nil
+	var errs []error
+
+	// Validate OrderBy
+	if i.OrderBy != "" {
+		validOrderBy := false
+		for _, orderBy := range []OrderBy{OrderByID, OrderByCreatedAt, OrderByUpdatedAt} {
+			if i.OrderBy == orderBy {
+				validOrderBy = true
+				break
+			}
+		}
+		if !validOrderBy {
+			errs = append(errs, fmt.Errorf("invalid order by: %s", i.OrderBy))
+		}
+	}
+
+	// Validate Order
+	if i.Order != "" {
+		if i.Order != OrderAsc && i.Order != OrderDesc {
+			errs = append(errs, fmt.Errorf("invalid order: %s", i.Order))
+		}
+	}
+
+	return errors.Join(errs...)
}

158-188: Complete the equality check to include metadata and annotations

The current implementation of Equal() compares namespace and entity relationships, but doesn't check if the optional metadata and annotations fields are equal.

func (i UpdatePlanAddonInput) Equal(p PlanAddon) bool {
	if i.Namespace != p.Namespace {
		return false
	}

	if i.PlanID != p.Plan.ID {
		return false
	}

	if i.AddonID != p.Addon.ID {
		return false
	}

	if i.FromPlanPhase != nil && *i.FromPlanPhase != p.FromPlanPhase {
		return false
	}

	if i.MaxQuantity == nil && p.MaxQuantity != nil {
		return false
	}

	if i.MaxQuantity != nil && p.MaxQuantity == nil {
		return false
	}

	if lo.FromPtr(i.MaxQuantity) != lo.FromPtr(p.MaxQuantity) {
		return false
	}

+	// Check metadata if provided
+	if i.Metadata != nil {
+		if !i.Metadata.Equal(p.Metadata) {
+			return false
+		}
+	}
+
+	// Check annotations if provided
+	if i.Annotations != nil {
+		if !i.Annotations.Equal(p.Annotations) {
+			return false
+		}
+	}

	return true
}

245-253: Standardize JSON field naming convention for consistency

The JSON field names for PlanID and AddonID use planID and addonID respectively, which differs from the camelCase convention used in other structs (planId, addonId). Consider standardizing to maintain consistency.

type DeletePlanAddonInput struct {
	models.NamespacedModel

	ID string `json:"id"`

-	PlanID string `json:"planID"`
+	PlanID string `json:"planId"`

-	AddonID string `json:"addonID"`
+	AddonID string `json:"addonId"`
}
openmeter/productcatalog/planaddon/event.go (2)

64-70: Standardize parameter naming in event constructors

For consistency, rename the parameter from addon to planAddon to match the naming convention used in NewPlanAddonCreateEvent.

// NewPlanAddonUpdateEvent creates a new PlanAddon update event
-func NewPlanAddonUpdateEvent(ctx context.Context, addon *PlanAddon) PlanAddonUpdateEvent {
+func NewPlanAddonUpdateEvent(ctx context.Context, planAddon *PlanAddon) PlanAddonUpdateEvent {
	return PlanAddonUpdateEvent{
-		PlanAddon: addon,
+		PlanAddon: planAddon,
		UserID:    session.GetSessionUserID(ctx),
	}
}

107-113: Standardize parameter naming in event constructors

For consistency, rename the parameter from addon to planAddon to match the naming convention used in NewPlanAddonCreateEvent.

// NewPlanAddonDeleteEvent creates a new PlanAddon delete event
-func NewPlanAddonDeleteEvent(ctx context.Context, addon *PlanAddon) PlanAddonDeleteEvent {
+func NewPlanAddonDeleteEvent(ctx context.Context, planAddon *PlanAddon) PlanAddonDeleteEvent {
	return PlanAddonDeleteEvent{
-		PlanAddon: addon,
+		PlanAddon: planAddon,
		UserID:    session.GetSessionUserID(ctx),
	}
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e3b2a1 and bd1fd5d.

📒 Files selected for processing (22)
  • openmeter/productcatalog/plan/adapter/mapping.go (1 hunks)
  • openmeter/productcatalog/plan/adapter/plan.go (3 hunks)
  • openmeter/productcatalog/plan/plan.go (1 hunks)
  • openmeter/productcatalog/planaddon.go (2 hunks)
  • openmeter/productcatalog/planaddon/adapter/adapter.go (1 hunks)
  • openmeter/productcatalog/planaddon/adapter/adapter_test.go (1 hunks)
  • openmeter/productcatalog/planaddon/adapter/mapping.go (1 hunks)
  • openmeter/productcatalog/planaddon/adapter/planaddon.go (1 hunks)
  • openmeter/productcatalog/planaddon/assert.go (1 hunks)
  • openmeter/productcatalog/planaddon/errors.go (1 hunks)
  • openmeter/productcatalog/planaddon/errors_test.go (1 hunks)
  • openmeter/productcatalog/planaddon/event.go (1 hunks)
  • openmeter/productcatalog/planaddon/planaddon.go (1 hunks)
  • openmeter/productcatalog/planaddon/repository.go (1 hunks)
  • openmeter/productcatalog/planaddon/service.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/addon.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/env.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/feature.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/meters.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/namespace.go (1 hunks)
  • openmeter/productcatalog/planaddon/testutils/plan.go (1 hunks)
  • openmeter/testutils/logger.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (13)
openmeter/productcatalog/plan/adapter/plan.go (1)
openmeter/productcatalog/plan/adapter/mapping.go (1)
  • FromPlanRow (15-68)
openmeter/productcatalog/planaddon/testutils/meters.go (3)
pkg/models/model.go (3)
  • ManagedResource (23-31)
  • NamespacedModel (180-182)
  • ManagedModel (107-113)
openmeter/productcatalog/planaddon/testutils/namespace.go (1)
  • NewTestULID (11-15)
openmeter/ent/db/meter/where.go (1)
  • ValueProperty (109-111)
openmeter/productcatalog/planaddon/errors_test.go (1)
openmeter/productcatalog/planaddon/errors.go (3)
  • NewNotFoundError (19-49)
  • NotFoundErrorParams (12-17)
  • IsNotFound (65-72)
openmeter/productcatalog/planaddon/testutils/addon.go (3)
openmeter/productcatalog/addon/service.go (1)
  • CreateAddonInput (98-101)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/productcatalog/addon.go (1)
  • AddonMeta (37-63)
openmeter/productcatalog/planaddon/testutils/plan.go (3)
openmeter/productcatalog/plan/service.go (1)
  • CreatePlanInput (98-101)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/productcatalog/plan.go (1)
  • PlanMeta (151-172)
openmeter/productcatalog/planaddon/repository.go (3)
pkg/framework/entutils/transaction.go (1)
  • TxCreator (176-176)
openmeter/productcatalog/planaddon/service.go (5)
  • ListPlanAddonsInput (41-80)
  • CreatePlanAddonInput (88-108)
  • DeletePlanAddonInput (245-253)
  • GetPlanAddonInput (212-223)
  • UpdatePlanAddonInput (133-156)
openmeter/productcatalog/planaddon/planaddon.go (1)
  • PlanAddon (14-25)
openmeter/productcatalog/plan/plan.go (3)
openmeter/productcatalog/plan.go (2)
  • Plan (39-44)
  • PlanMeta (151-172)
openmeter/productcatalog/phase.go (1)
  • Phase (91-96)
openmeter/productcatalog/plan/phase.go (1)
  • Phase (62-65)
openmeter/productcatalog/planaddon/assert.go (4)
openmeter/productcatalog/planaddon/service.go (2)
  • CreatePlanAddonInput (88-108)
  • UpdatePlanAddonInput (133-156)
openmeter/productcatalog/planaddon/planaddon.go (1)
  • PlanAddon (14-25)
openmeter/productcatalog/plan/plan.go (1)
  • Plan (16-24)
openmeter/ent/db/planaddon/where.go (1)
  • MaxQuantity (104-106)
openmeter/productcatalog/planaddon/adapter/mapping.go (6)
openmeter/productcatalog/planaddon/planaddon.go (1)
  • PlanAddon (14-25)
pkg/models/model.go (1)
  • ManagedModel (107-113)
openmeter/productcatalog/planaddon.go (2)
  • PlanAddonMeta (10-15)
  • PlanAddonConfig (17-23)
openmeter/productcatalog/plan/adapter/mapping.go (1)
  • FromPlanRow (15-68)
openmeter/productcatalog/addon/adapter/mapping.go (1)
  • FromAddonRow (15-65)
pkg/models/validator.go (1)
  • Validate (16-26)
openmeter/productcatalog/planaddon/planaddon.go (5)
pkg/models/model.go (1)
  • ManagedModel (107-113)
openmeter/productcatalog/planaddon.go (1)
  • PlanAddonMeta (10-15)
openmeter/productcatalog/plan/plan.go (1)
  • Plan (16-24)
pkg/models/validator.go (1)
  • Validate (16-26)
pkg/models/error.go (1)
  • NewNillableGenericValidationError (129-135)
openmeter/productcatalog/planaddon/service.go (4)
openmeter/productcatalog/planaddon/planaddon.go (1)
  • PlanAddon (14-25)
pkg/sortx/order.go (1)
  • Order (3-3)
pkg/models/validator.go (1)
  • Validate (16-26)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/productcatalog/planaddon.go (2)
openmeter/ent/db/planaddon/where.go (1)
  • MaxQuantity (104-106)
pkg/models/validator.go (3)
  • CustomValidator (12-14)
  • ValidatorFunc (10-10)
  • Validate (16-26)
openmeter/productcatalog/planaddon/testutils/env.go (4)
openmeter/watermill/eventbus/eventbus.go (2)
  • Publisher (61-73)
  • NewMock (150-162)
openmeter/testutils/pg_driver.go (2)
  • TestDB (54-58)
  • InitPostgresDB (60-96)
openmeter/testutils/logger.go (1)
  • NewDiscardLogger (14-18)
openmeter/productcatalog/adapter/feature.go (1)
  • NewPostgresFeatureRepo (33-38)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (31)
openmeter/testutils/logger.go (1)

17-28: Excellent implementation of a discard logger for testing

The implementation of discardHandler as a no-op logger is clean and properly implements all required methods of the slog.Handler interface. The TODO comment explaining that this is a temporary solution until the project upgrades to Go 1.24 is particularly helpful for future maintenance.

openmeter/productcatalog/plan/adapter/plan.go (3)

149-149: Function reference updated correctly

The function call has been updated from fromPlanRow to FromPlanRow to use the newly exported function.


194-194: Function reference updated correctly

The function call has been updated from fromPlanRow to FromPlanRow to use the newly exported function.


386-386: Function reference updated correctly

The function call has been updated from fromPlanRow to FromPlanRow to use the newly exported function.

openmeter/productcatalog/plan/adapter/mapping.go (1)

15-15: Good function export to enable reuse

Exporting the FromPlanRow function is a proper refactoring to enable its reuse in the new planaddon adapter. This follows good software design principles by promoting code reuse.

openmeter/productcatalog/planaddon/testutils/addon.go (1)

14-34: Test utility looks good.

The NewTestAddon function provides a properly structured test utility for creating addon test data with a consistent set of default values. The function correctly uses t.Helper() to improve error reporting in tests and initializes all the necessary fields for the CreateAddonInput struct.

openmeter/productcatalog/planaddon/testutils/plan.go (1)

14-31: Test utility implementation looks good.

The NewTestPlan function provides a properly structured test utility for creating plan test data with a consistent set of default values. The function correctly uses t.Helper() to improve error reporting in tests and initializes all the necessary fields for the CreatePlanInput struct.

openmeter/productcatalog/planaddon/testutils/namespace.go (2)

11-15: ULID generation utility looks good.

The NewTestULID function properly creates unique, lexicographically sortable identifiers for testing purposes using a cryptographically secure random source and current timestamp.


17-17: Alias variable is a good convenience.

Creating an alias for the ULID generator as NewTestNamespace makes the code more readable when using it specifically for namespace generation.

openmeter/productcatalog/planaddon/adapter/mapping.go (3)

17-57: Plan setup looks good.

The function correctly maps the database entity fields to the domain model and properly sets up the Plan reference, both with a basic ID reference and with the full object when the edge is loaded.


67-78: Addon edge handling looks good.

The function properly handles the Addon edge, including error checking and nil checks. It follows the same pattern used for the Plan edge handling.


80-85: Domain model validation looks good.

The function correctly validates the resulting PlanAddon object before returning it, with proper error wrapping that includes the namespace and ID to aid debugging.

openmeter/productcatalog/planaddon/testutils/feature.go (2)

12-20: Good implementation of a reusable test feature creator.

The NewTestFeature function creates a standardized test feature with consistent naming conventions. This is a good practice for test utilities as it reduces duplication in test code.


22-33: Well-structured feature creation from meter properties.

This helper function properly maps meter properties to feature inputs, including the use of lo.ToPtr() to safely convert the meter key to a pointer. The empty metadata map initialization is also a good practice to avoid nil map references.

openmeter/productcatalog/planaddon/errors_test.go (1)

11-46: LGTM! Comprehensive test for error type detection.

This test validates both direct and wrapped instances of the NotFoundError are correctly identified, as well as confirming that other error types are not misidentified. The table-driven approach makes it easy to add more test cases in the future.

openmeter/productcatalog/planaddon/repository.go (1)

10-18: Well-designed repository interface with transactional support.

The Repository interface follows a clean design pattern with:

  1. Embedded TxCreator for transactional operations
  2. Comprehensive CRUD operations with consistent naming
  3. Structured input types for flexibility and maintainability

This approach ensures that implementations will provide consistent behavior while allowing for different storage backends.

openmeter/productcatalog/planaddon/adapter/adapter_test.go (4)

1-3: LGTM: Clear package declaration.

Package declaration and basic imports are set up correctly.


27-37: LGTM: Well-structured test setup.

The test setup pattern follows good practices with context creation, cancellation, environment setup, and database migrations.


310-321: LGTM: Well-structured PlanAddon input.

The PlanAddon input configuration is clear and comprehensive, including essential fields like namespace, annotations, IDs, and phase configurations.


323-329: LGTM: Thorough validation of created PlanAddon.

The test correctly creates a PlanAddon and verifies it's not nil before asserting equality with the input.

openmeter/productcatalog/planaddon/errors.go (3)

1-11: LGTM: Good error interface implementation.

The error implementation correctly satisfies the error interface with proper type assertion.


51-63: LGTM: Proper error implementation.

The NotFoundError struct correctly implements the error interface with Error() and Unwrap() methods.


65-72: LGTM: Effective error type checking.

The IsNotFound function properly uses errors.As to check if an error is a NotFoundError.

openmeter/productcatalog/planaddon.go (1)

10-16: LGTM: Clear metadata structure.

The PlanAddonMeta struct provides a good organization of metadata, annotations, and configuration.

openmeter/productcatalog/planaddon/assert.go (1)

1-8: LGTM: Proper package and imports.

Package declaration and imports are appropriate for assertion helpers.

openmeter/productcatalog/planaddon/planaddon.go (1)

27-51: Validation approach is well-structured.

This function systematically delegates field validations and collects errors, which is a solid approach for centralized validation.

openmeter/productcatalog/planaddon/adapter/adapter.go (1)

1-84: No major concerns found.

The adapter configuration and transaction methods appear robust. Dependency checks for nil Client and Logger are appropriate, and the interface compliance is clearly enforced.

openmeter/productcatalog/planaddon/testutils/env.go (1)

1-136: Test environment approach looks good.

This code provides a comprehensive in-test environment with proper initialization, schema migration, and teardown mechanisms. No issues detected.

openmeter/productcatalog/planaddon/adapter/planaddon.go (1)

21-412: All other implementations look correct.

CRUD operations and eager-loading strategies appear consistent, with user-friendly error handling for missing or invalid resources.

openmeter/productcatalog/planaddon/service.go (1)

143-156: LGTM! The structure of UpdatePlanAddonInput correctly supports partial updates.

The fields that can be updated are properly marked as pointers, allowing for clear distinction between fields that should be updated and those that shouldn't.

openmeter/productcatalog/planaddon/event.go (1)

44-44:

Details

✅ Verification successful

Verify entity type in resource path

The resource path is using metadata.EntityAddon as the entity type, but since this is a PlanAddon, consider if a more appropriate entity type like metadata.EntityPlanAddon should be used (if such a constant exists).

Also applies to: 87-87, 130-130


🏁 Script executed:

#!/bin/bash
# Check if EntityPlanAddon exists in the codebase
grep -r "EntityPlanAddon" --include="*.go" .

# List all available entity types
grep -r "Entity[A-Z]" --include="*.go" ./openmeter/event/metadata/

Length of output: 1004


Entity Type Verification for PlanAddon Events

After verifying the codebase with the provided script, it appears that no constant named EntityPlanAddon exists. The metadata package defines separate constants for plans (EntityPlan) and addons (EntityAddon), and the current usage of metadata.EntityAddon in the resource path is consistent with the codebase.

If you intended for plan addons to have a distinct resource type, you might consider defining a new constant (e.g., EntityPlanAddon) in the metadata package. Otherwise, retaining metadata.EntityAddon is acceptable.

This check applies to the affected locations at:

  • openmeter/productcatalog/planaddon/event.go line 44
  • and similarly at lines 87 and 130.

GAlexIHU
GAlexIHU previously approved these changes Apr 16, 2025
Comment thread openmeter/productcatalog/plan/plan.go Resolved
@chrisgacsal
chrisgacsal merged commit 3aec028 into main Apr 16, 2025
@chrisgacsal
chrisgacsal deleted the feat/productcatalog branch April 16, 2025 10:49
@coderabbitai coderabbitai Bot mentioned this pull request Sep 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants