Repository navigation
feat: enable planaddon HTTP API - #2684
Conversation
📝 WalkthroughWalkthroughThis change introduces full API, HTTP handler, router, and service integration for managing plan add-ons within the product catalog. It adds support for listing, creating, updating, deleting, and retrieving plan add-ons, with enhanced capabilities for filtering, ordering, and pagination. The API schemas and OpenAPI specifications are updated to reflect these features, including a new paginated response type and a read-only annotations property on plan add-ons. The Go server is wired to include the new plan add-on service, and new HTTP driver files implement the request handling and mapping logic. The router is updated to delegate plan add-on endpoints to these handlers. Changes
Possibly related PRs
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 (1)
🧰 Additional context used🧬 Code Graph Analysis (1)openmeter/server/server_test.go (2)
⏰ Context from checks skipped due to timeout of 90000ms (13)
🔇 Additional comments (4)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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: 5
🧹 Nitpick comments (11)
api/spec/src/productcatalog/planaddon.tsp (1)
21-28: Document the plan for metadata field implementation.The commented-out metadata field has a FIXME note, but no additional context on when or how it will be implemented.
Consider adding a more detailed comment explaining:
- The reason for disabling this field currently
- The conditions needed to enable it
- Any tracking issue number for reference
app/common/productcatalog.go (1)
104-126: Fix inconsistent naming in logger and error message.There are two minor inconsistencies in the service initialization:
- The error message refers to "add-on adapter" but should be "plan add-on adapter" for clarity.
- The logger subsystem is set to "productcatalog.addon" but should be "productcatalog.planaddon" to be consistent with the adapter initialization.
if err != nil { - return nil, fmt.Errorf("failed to initialize add-on adapter: %w", err) + return nil, fmt.Errorf("failed to initialize plan add-on adapter: %w", err) } return planaddonservice.New(planaddonservice.Config{ Adapter: adapter, Plan: planService, Addon: addonService, - Logger: logger.With("subsystem", "productcatalog.addon"), + Logger: logger.With("subsystem", "productcatalog.planaddon"), Publisher: publisher, })openmeter/productcatalog/planaddon/httpdriver/driver.go (1)
34-38: Consider using a more specific error message.The current error message is generic ("internal server error") and doesn't indicate what actually went wrong. A more descriptive message would help with debugging.
- return "", commonhttp.NewHTTPError(http.StatusInternalServerError, errors.New("internal server error")) + return "", commonhttp.NewHTTPError(http.StatusInternalServerError, errors.New("failed to resolve namespace from context"))api/openapi.yaml (1)
6889-6949: Ensure explicit explode setting for array query parameters
Theidandkeyparameters are defined as arrays withstyle: formbut lack an explicitexplode: false. Depending on the server/client defaults, this could change how CSV values are parsed vs. repeated parameters. To avoid ambiguity, addexplode: falseto both parameters.Proposed diff:
- name: id in: query required: false description: Filter by addon.id attribute. schema: type: array items: type: string pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ description: ULID (Universally Unique Lexicographically Sortable Identifier). example: 01G65Z755AFWAKHE12NY0CQ9FH - style: form + style: form + explode: false - name: key in: query required: false description: Filter by addon.key attribute. schema: type: array items: type: string minLength: 1 maxLength: 64 pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ description: A key is a unique string that is used to identify a resource. - style: form + style: form + explode: falseapi/openapi.cloud.yaml (3)
6891-6942: Explicitly specifyexplodefor array query parameters to ensure consistent serialization.The
idandkeyparameters definestyle: formbut omitexplode. By default, form-style arrays useexplode=true(e.g.,id=A&id=B), whereasexplode=falseyields comma-separated values (id=A,B). To avoid ambiguity and align with your API client expectations, consider adding:- name: id in: query required: false description: Filter by addon.id attribute. schema: type: array items: type: string pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ description: ULID... style: form explode: false - name: key in: query required: false description: Filter by addon.key attribute. schema: type: array items: type: string minLength: 1 maxLength: 64 pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ style: form explode: false
10664-10683: Clarify component parameter naming for ordering.The parameters live under
components/parameters/PlanAddonOrderByOrdering, which combines “OrderBy” and “Ordering” and can be confusing. For better readability, consider renaming the component to something likePlanAddonOrdering(orPlanAddonListOrdering):- PlanAddonOrderByOrdering.order: + PlanAddonOrdering.order: - PlanAddonOrderByOrdering.orderBy: + PlanAddonOrdering.orderBy:This streamlines the naming and clearly conveys the intent of these query parameters.
17948-17983: Enhance schema documentation with examples and defaults.
- Add an
exampleto thePlanAddonOrderByenum for clarity:example: created_at- Indicate that
itemsin the paginated response may be empty by adding a default:items: type: array items: $ref: '#/components/schemas/PlanAddon' description: The items in the current page. default: []These tweaks will improve API documentation and help client generators produce more accurate stubs.
api/client/javascript/src/client/schemas.ts (1)
18873-18898: Comprehensive filtering capabilities for the list operation.The updated
listPlanAddonsoperation now supports a rich set of filtering options including:
- Inclusion of deleted items
- Filtering by ID or key
- Pagination and sorting
The
keyVersionparameter has a more complex structure that allows filtering by both key and version. Consider adding a code example in the documentation to illustrate how to use this parameter effectively./** @description Filter by addon.key and addon.version attributes. */ keyVersion?: { [key: string]: number[] + // Example: { "basic": [1, 2], "premium": [3] } to filter for basic v1/v2 and premium v3 }openmeter/productcatalog/planaddon/httpdriver/planaddon.go (3)
106-110: Limit the JSON request body size to mitigate DoS risk
commonhttp.JSONRequestBodyDecoderreads the entire body; an attacker can send an arbitrarily large payload.
Wrap the body withhttp.MaxBytesReader(or add a size‑aware decoder) before decoding.- body := api.PlanAddonCreate{} - if err := commonhttp.JSONRequestBodyDecoder(r, &body); err != nil { + const maxBody = 1 << 20 // 1 MiB – adjust as appropriate + r.Body = http.MaxBytesReader(nil, r.Body, maxBody) + + var body api.PlanAddonCreate + if err := commonhttp.JSONRequestBodyDecoder(r, &body); err != nil { return CreatePlanAddonRequest{}, fmt.Errorf("failed to decode create plan add-on assignment request: %w", err) }
112-116: Minor: error message includes an (unresolved) namespaceWhen
resolveNamespacefails,nsis expected to be empty, so printing it adds no value and slightly clutters logs.
Consider omitting the placeholder or logging the underlying error only.
198-200: Preferstruct{}overinterface{}for empty responses
interface{}permits any value and slightly weakens type‑safety.
Usingstruct{}conveys intent (always empty) and prevents accidental payloads:-type ( - DeletePlanAddonResponse = interface{} +type ( + DeletePlanAddonResponse = struct{}(and return
struct{}{}instead ofnil).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
api/client/javascript/src/client/schemas.ts(7 hunks)api/openapi.cloud.yaml(4 hunks)api/openapi.yaml(4 hunks)api/spec/src/productcatalog/planaddon.tsp(2 hunks)api/spec/src/productcatalog/routes.tsp(1 hunks)app/common/productcatalog.go(3 hunks)cmd/server/main.go(1 hunks)cmd/server/wire.go(2 hunks)cmd/server/wire_gen.go(4 hunks)openmeter/productcatalog/planaddon/httpdriver/driver.go(1 hunks)openmeter/productcatalog/planaddon/httpdriver/errors.go(1 hunks)openmeter/productcatalog/planaddon/httpdriver/mapping.go(1 hunks)openmeter/productcatalog/planaddon/httpdriver/planaddon.go(1 hunks)openmeter/server/router/planaddon.go(1 hunks)openmeter/server/router/router.go(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
cmd/server/wire.go (4)
app/common/productcatalog.go (1)
PlanAddon(45-47)openmeter/ent/db/predicate/predicate.go (1)
PlanAddon(210-210)openmeter/productcatalog/addon/service.go (1)
Service(35-44)openmeter/productcatalog/plan/service.go (1)
Service(35-44)
cmd/server/main.go (4)
app/common/productcatalog.go (1)
PlanAddon(45-47)api/api.gen.go (1)
PlanAddon(4930-4964)openmeter/ent/db/predicate/predicate.go (1)
PlanAddon(210-210)api/client/go/client.gen.go (1)
PlanAddon(4483-4517)
openmeter/productcatalog/planaddon/httpdriver/errors.go (2)
pkg/framework/commonhttp/errors.go (1)
HandleErrorIfTypeMatches(62-75)openmeter/productcatalog/feature/feature.go (1)
FeatureNotFoundError(11-13)
openmeter/server/router/planaddon.go (3)
openmeter/server/router/router.go (1)
Router(201-224)api/api.gen.go (1)
ListPlanAddonsParams(7363-7393)openmeter/productcatalog/planaddon/httpdriver/planaddon.go (3)
DeletePlanAddonParams(194-197)GetPlanAddonParams(238-241)UpdatePlanAddonParams(145-148)
openmeter/productcatalog/planaddon/httpdriver/driver.go (3)
openmeter/productcatalog/planaddon/httpdriver/planaddon.go (5)
ListPlanAddonsHandler(33-33)CreatePlanAddonHandler(101-101)DeletePlanAddonHandler(199-199)GetPlanAddonHandler(243-243)UpdatePlanAddonHandler(150-150)pkg/framework/transport/httptransport/options.go (1)
HandlerOption(19-21)pkg/framework/commonhttp/errors.go (1)
NewHTTPError(35-41)
openmeter/server/router/router.go (2)
openmeter/productcatalog/addon/service/service.go (1)
New(19-42)pkg/framework/transport/httptransport/options.go (1)
WithErrorHandler(29-33)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (2)
PlanAddonOrderBy(4983-4983)PlanAddonPaginatedResponse(4986-4998)api/client/go/client.gen.go (2)
PlanAddonOrderBy(4536-4536)PlanAddonPaginatedResponse(4539-4551)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: CI
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Lint
- GitHub Check: Analyze (go)
🔇 Additional comments (27)
cmd/server/wire.go (2)
32-32: LGTM: Import added for the planaddon package.This import allows the application to use the planaddon service, which is part of the broader plan add-on assignment HTTP API implementation.
67-67: LGTM: New PlanAddon field added to Application struct.The PlanAddon service field is correctly added to the Application struct, following the same pattern as other services in the codebase. This allows the service to be properly injected and accessed by the application.
cmd/server/main.go (1)
170-170: LGTM: PlanAddon service correctly wired to router configuration.The PlanAddon service is correctly added to the RouterConfig struct, following the established pattern for other services. This enables HTTP routes to access the service implementation.
api/spec/src/productcatalog/planaddon.tsp (2)
14-20: LGTM: Added annotations field with appropriate visibility.The annotations field is properly defined as a read-only property with clear documentation indicating it's managed by the system and cannot be modified by users.
81-91: LGTM: Well-defined PlanAddonOrderBy enum for listing operations.The PlanAddonOrderBy enum properly defines the available ordering options for plan add-on listings, which will be used for the HTTP API's filtering and sorting capabilities.
openmeter/productcatalog/planaddon/httpdriver/errors.go (1)
12-16:Details
❌ Incorrect review comment
Verify the error type match is correct for this context.
The error encoder is specifically handling
*feature.FeatureNotFoundErrorin a plan add-on context. Is this the correct error type, or should there be a more specificplanaddon.NotFoundError?
🏁 Script executed:
#!/bin/bash # Check if there are any usage patterns of FeatureNotFoundError in planaddon package rg -A 3 "FeatureNotFoundError" --glob "openmeter/productcatalog/planaddon/**/*.go" # Check if plan add-on service uses feature service rg -A 3 "feature\.(Service|FeatureConnector)" --glob "openmeter/productcatalog/planaddon/**/*.go"Length of output: 761
Ignore the suggestion to introduce
planaddon.NotFoundError.There is no
planaddon.NotFoundErrordefined in the codebase—onlyfeature.FeatureNotFoundErrorexists. Handling*feature.FeatureNotFoundErrorin openmeter/productcatalog/planaddon/httpdriver/errors.go is correct.
- File needing no change:
openmeter/productcatalog/planaddon/httpdriver/errors.goLikely an incorrect or invalid review comment.
cmd/server/wire_gen.go (1)
29-29: Well-integrated service initialization!The new
planaddonservice is properly integrated into the application's dependency injection setup. The initialization follows the existing pattern with appropriate error handling and cleanup procedures.Also applies to: 382-392, 458-458
openmeter/server/router/planaddon.go (4)
11-17: LGTM! ListPlanAddons implementation.The handler properly maps API parameters to the service's expected format.
21-22: LGTM! CreatePlanAddon implementation.Simple and correct delegation to the handler.
27-31: LGTM! DeletePlanAddon implementation.Correctly maps the path parameters to the expected DeletePlanAddonParams structure.
36-40: LGTM! GetPlanAddon implementation.Proper handling of plan and addon identifiers that might be either IDs or keys.
openmeter/server/router/router.go (1)
48-49: LGTM! Well-integrated router extension.The plan addon service and handler are properly integrated into the router with appropriate validation and configuration. The pattern is consistent with other services in the router.
Also applies to: 101-101, 174-176, 210-210, 352-356
app/common/productcatalog.go (1)
20-22: LGTM! Clean integration of PlanAddon dependency.The PlanAddon service is properly added to the dependency injection framework with appropriate imports and wire sets.
Also applies to: 30-30, 45-47
api/spec/src/productcatalog/routes.tsp (1)
178-208: LGTM: Well-structured API endpoint design with comprehensive filtering and pagination.The changes to the PlanAddons list method correctly implement filtering, pagination, and ordering capabilities consistent with other API endpoints in the codebase. The parameters follow established patterns used in similar interfaces (Plans, Addons) and provide appropriate documentation for each option.
openmeter/productcatalog/planaddon/httpdriver/mapping.go (2)
55-55: Consider using the request's FromPlanPhase value.In the create request mapping, FromPlanPhase is set to an empty string rather than using the value from the request. This might be intentional, but differs from the update request which preserves the value.
Please verify if FromPlanPhase should be initialized from the request:
- FromPlanPhase: "", + FromPlanPhase: a.FromPlanPhase,
33-45: Good defensive coding to avoid nil pointer dereferences.The FromAnnotations function correctly handles empty annotations by returning a non-nil pointer to an empty map, which is a good practice to prevent nil pointer dereferences in client code.
openmeter/productcatalog/planaddon/httpdriver/driver.go (2)
14-24: LGTM: Well-designed interface hierarchy for PlanAddon HTTP handlers.The interface design follows good separation of concerns with a main Handler interface extending the specific PlanAddonHandler interface. The method signatures correspond to standard REST operations and match the handler types defined elsewhere.
43-53: LGTM: Clean constructor with proper dependency injection.The constructor function takes the required dependencies and optional handler options, following good dependency injection patterns. The handler struct is properly initialized with all necessary components.
api/openapi.yaml (2)
18241-18246: Add annotations property to PlanAddon schema
The addition of the read-onlyannotationsproperty correctly surfaces system-managed metadata on plan add-ons. TheallOfreference to the commonAnnotationsschema and thereadOnly: trueflag align with the intended design.
18325-18360: Introduce PlanAddonOrderBy enum and Paginated Response schema
ThePlanAddonOrderByenum lists all sortable fields, andPlanAddonPaginatedResponseencapsulates pagination metadata (totalCount,page,pageSize,items). This structured approach aligns well with API best practices for filtering, sorting, and pagination.api/openapi.cloud.yaml (1)
17864-17870: VerifyAnnotationsschema is defined and correctly modeled.The new
annotationsproperty references#/components/schemas/Annotations. Please confirm that you have defined anAnnotationsschema (for example, as an object withadditionalProperties: { type: string }). If it’s missing, add:Annotations: type: object additionalProperties: type: string description: Map of system-managed key-value annotations.api/client/javascript/src/client/schemas.ts (4)
7203-7207: LGTM: The new readonly annotations property is well-defined.The addition of a system-managed, read-only annotations property to the PlanAddon schema is a good practice for extending the model with metadata that should be protected from user modification.
7274-7298: The pagination and ordering structures align with API best practices.The newly added
PlanAddonOrderByenum andPlanAddonPaginatedResponsetype provide essential pagination and sorting capabilities for the plan add-on API. The pagination structure includes all the necessary fields for client-side handling of paginated results.Note that the enum values use snake_case ('created_at', 'updated_at') rather than camelCase, which is presumably to match the API's query parameter format.
9422-9424: Consistent parameter definitions for ordering.The parameter definitions and corresponding exported types for ordering plan add-ons are properly defined and will enable strong typing for API consumers.
Also applies to: 10091-10094
18913-18913: Response type updated to match new paginated structure.The response type has been correctly updated to use the new paginated response structure, which is consistent with the backend API changes.
openmeter/productcatalog/planaddon/httpdriver/planaddon.go (2)
50-55:PlanIDsandPlanKeysare both populated – may unintentionally filter everything outBoth fields are filled with the same
PlanIDOrKeyvalue.
If the service layer treats the two filters as an AND (ID and key must match), every request where the caller supplies either an ID or a key—but not both—will return an empty list.Double‑check the semantics in
planaddon.Service.ListPlanAddons. If it is indeed an intersection, populate only one of the slices (or make the service treat them as a union).
126-133: Potential nil‑pointer dereference fromservice.CreatePlanAddon
CreatePlanAddonreturns(*planaddon.PlanAddon, error). If it (unexpectedly) returns(nil, nil)you’ll dereference*aand panic.Either:
if a == nil { return CreatePlanAddonResponse{}, errors.New("service returned nil plan add‑on") } return FromPlanAddon(*a)or make the service guarantee a non‑nil result.
66fba09 to
214ad49
Compare
Overview
Summary by CodeRabbit
New Features
Enhancements