Repository navigation
Customer Access API - #2546
Customer Access API#2546
Conversation
📝 WalkthroughWalkthroughThis pull request extends the API with a new endpoint at Changes
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 ✨ 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 (
|
1408bf5 to
4c071dd
Compare
| return c.entitlementRepo.ListEntitlements(ctx, params) | ||
| } | ||
|
|
||
| func (c *entitlementConnector) GetAccess(ctx context.Context, namespace string, subjectKey string) (Access, error) { |
There was a problem hiding this comment.
this is the interesting part
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (12)
api/openapi.yaml (1)
12945-12985: EntitlementValueWithId Schema AdditionThe introduction of the
EntitlementValueWithIdschema is comprehensive. It correctly mandates the presence ofhasAccessandid, and defines supplementary properties (balance,usage,overage,config) with appropriate types, formats, and descriptions.A couple of nitpicks:
- Naming Consistency: The description uses “EntitlementValueWithID” (with uppercase “ID”), whereas the schema name uses “EntitlementValueWithId”. Consider standardizing the naming convention to avoid any potential confusion.
- Example Format for
config: The provided example{ key: "value" }might not be interpreted as valid JSON since JSON requires keys to be quoted. Adjusting it to a valid JSON example (e.g.,{ "key": "value" }) could be beneficial.openmeter/entitlement/access.go (3)
3-6: The Access struct is well-defined, consider adding more documentation.The struct definition is clean and follows Go conventions. The map design allows for flexible feature key mapping. However, consider adding more comprehensive documentation to clarify:
- The purpose and lifecycle of the Access struct
- Expected format of feature keys
- Any constraints on the map contents
type Access struct { - // Map of featureKey to entitlement value + ID + // Access represents the collection of features a customer has access to. + // Entitlements maps feature keys (string identifiers for specific features) + // to their corresponding entitlement values and IDs. Entitlements map[string]EntitlementValueWithId }
8-11: EntitlementValueWithId type looks good, consider adding field comments.The struct is well-structured with a clear purpose of extending EntitlementValue with an ID. Adding field comments would improve documentation and make the code more self-explanatory.
type EntitlementValueWithId struct { - Value EntitlementValue - ID string + // Value represents the entitlement value associated with a feature + Value EntitlementValue + // ID uniquely identifies the entitlement + ID string }
1-12: Consider adding validation methods.While the structure is well-defined, there are no validation methods for ensuring data integrity. Consider adding methods to validate the Access and EntitlementValueWithId structs, especially if they will be populated from external inputs.
You could add validation methods like:
// Validate ensures the Access struct contains valid data func (a Access) Validate() error { if a.Entitlements == nil { return errors.New("entitlements map cannot be nil") } for key, value := range a.Entitlements { if key == "" { return errors.New("feature key cannot be empty") } if err := value.Validate(); err != nil { return fmt.Errorf("invalid entitlement for feature '%s': %w", key, err) } } return nil } // Validate ensures the EntitlementValueWithId contains valid data func (e EntitlementValueWithId) Validate() error { if e.ID == "" { return errors.New("entitlement ID cannot be empty") } // Assuming EntitlementValue has its own validation method if err := e.Value.Validate(); err != nil { return fmt.Errorf("invalid entitlement value: %w", err) } return nil }api/openapi.cloud.yaml (2)
2918-2990: New Customer Access Endpoint DefinitionThe addition of the
/api/v1/customers/{customerIdOrKey}/accessendpoint is well-structured. TheGETmethod is clearly defined with:
- A specific
operationId(getCustomerAccess)- A concise summary and description
- Proper parameter validation (using
minLength,maxLength, and a regex pattern) forcustomerIdOrKey- Detailed response definitions with appropriate HTTP status codes and response schemas (particularly the reference to
CustomerAccessin the 200 response)Make sure that the regex pattern truly reflects your customer ID/key formats and that your server logic validates it accordingly.
12966-13006: Detailed Specification for EntitlementValueWithId SchemaThe
EntitlementValueWithIdschema is comprehensively defined with:
- Mandatory fields (
hasAccessandid)- Additional fields such as
balance,usage,overage, andconfigwith clear descriptions and examples- A regex pattern ensuring the proper format for the
idOne minor suggestion: correct the typo in the description for
hasAccess("Shared accross all entitlement types" should be "Shared across all entitlement types") to improve clarity.openmeter/entitlement/access_test.go (1)
1-271: Consider extracting common test setup patterns.The test file has excellent coverage but contains some repetitive setup code across test cases. Consider refactoring common patterns like feature creation and entitlement creation into helper methods to improve maintainability and readability.
Example refactoring:
+ // Helper function to create a feature + func createTestFeature(t *testing.T, deps *testDependencies, namespace, key string) *feature.Feature { + feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + Key: key, + Name: "test", + Namespace: namespace, + MeterSlug: lo.ToPtr("meter1"), + }) + require.NoError(t, err) + require.NotNil(t, feat) + return feat + } + + // Helper function to create a boolean entitlement + func createTestBoolEntitlement(t *testing.T, conn entitlement.Connector, namespace, subjectKey, featureKey string, featureID string) *entitlement.Entitlement { + ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, + SubjectKey: subjectKey, + FeatureKey: lo.ToPtr(featureKey), + FeatureID: &featureID, + EntitlementType: entitlement.EntitlementTypeBoolean, + }) + require.NoError(t, err) + require.NotNil(t, ent) + return ent + }You could then simplify your test code:
- feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ - Key: featureKey, - Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), - }) - require.NoError(t, err) - require.NotNil(t, feat) + feat := createTestFeature(t, deps, ns, featureKey) - ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, - SubjectKey: subjectKey, - FeatureKey: &featureKey, - FeatureID: &feat.ID, - EntitlementType: entitlement.EntitlementTypeBoolean, - }) - require.NoError(t, err) - require.NotNil(t, ent) + ent := createTestBoolEntitlement(t, conn, ns, subjectKey, featureKey, feat.ID)openmeter/entitlement/connector.go (1)
231-315: Efficient concurrency with suggested refinements.
- The concurrency limit approach (lines 247-249) provides control, but consider making
maxConcurrencyconfigurable to accommodate varied system loads.- Your
sync.Mapusage and type checks (lines 291-303) are handled properly, helping avoid data races. Periodically evaluate potential overhead ifentitlementsgrows large.Would you like me to open a new issue for making the concurrency limit environment-configurable?
api/client/javascript/src/client/schemas.ts (2)
604-623: Clarify documentation for the newly added endpoint.The JSDoc annotation says "Get the access of a customer to a given feature (by key)." However, this endpoint returns all entitlements under
CustomerAccess. Consider updating the description to emphasize that it fetches all entitlements, rather than a single feature’s access.
4176-4212: Fix minor typos in documentation.There are a couple of small typographical errors in the docstrings ("accross" → "across," "it's value" → "its value"). Applying the following patch improves clarity:
- * @description Whether the subject has access to the feature. Shared accross all entitlement types. + * @description Whether the subject has access to the feature. Shared across all entitlement types. - ... Balance represents the remaining balance of the entitlement, it's value never turns negative. + ... Balance represents the remaining balance of the entitlement, its value never turns negative.api/spec/src/entitlements/customer.tsp (2)
14-25: Documentation references an implied 'hasAccess' property inEntitlementValue.
Make sure thatEntitlementValuedoes indeed define a property such ashasAccess, so this documentation remains accurate and clear.
44-49: Specify record key type for clarity (optional).
Currently, you’re usingRecord<EntitlementValueWithId>without explicitly typing the record’s key. For added clarity, consider specifying the key type if allowed by TypeSpec (e.g.,Record<Key, EntitlementValueWithId>) to make it explicit that the key must be a feature key.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
api/client/javascript/src/client/schemas.ts(6 hunks)api/openapi.cloud.yaml(4 hunks)api/openapi.yaml(4 hunks)api/spec/src/cloud/main.tsp(1 hunks)api/spec/src/customer.tsp(0 hunks)api/spec/src/entitlements/customer.tsp(1 hunks)api/spec/src/entitlements/main.tsp(1 hunks)e2e/productcatalog_test.go(2 hunks)openmeter/customer/httpdriver/apimapping.go(2 hunks)openmeter/customer/httpdriver/customer.go(1 hunks)openmeter/customer/httpdriver/handler.go(1 hunks)openmeter/customer/service.go(1 hunks)openmeter/customer/service/customer.go(2 hunks)openmeter/entitlement/access.go(1 hunks)openmeter/entitlement/access_test.go(1 hunks)openmeter/entitlement/connector.go(3 hunks)openmeter/entitlement/utils_test.go(4 hunks)openmeter/server/router/customer.go(0 hunks)openmeter/server/router/entitlement.go(2 hunks)openmeter/server/server_test.go(2 hunks)
💤 Files with no reviewable changes (2)
- api/spec/src/customer.tsp
- openmeter/server/router/customer.go
🧰 Additional context used
🧬 Code Definitions (7)
openmeter/customer/httpdriver/handler.go (1)
openmeter/customer/httpdriver/customer.go (1)
GetCustomerAccessHandler(364-364)
openmeter/entitlement/utils_test.go (4)
openmeter/server/server_test.go (1)
MockStreamingConnector(572-572)openmeter/streaming/testutils/streaming.go (2)
MockStreamingConnector(32-35)NewMockStreamingConnector(19-24)api/api.gen.go (1)
MeterAggregationSum(434-434)openmeter/meter/meter.go (1)
MeterAggregationSum(19-19)
openmeter/customer/httpdriver/apimapping.go (2)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)
openmeter/server/server_test.go (2)
openmeter/entitlement/access.go (1)
Access(3-6)openmeter/customer/customer.go (1)
GetCustomerInput(212-216)
openmeter/customer/httpdriver/customer.go (4)
openmeter/customer/customer.go (2)
GetCustomerInput(212-216)CustomerIDOrKey(109-112)api/api.gen.go (1)
CustomerAccess(1823-1827)openmeter/customer/httpdriver/apimapping.go (1)
MapAccessToAPI(94-116)pkg/framework/commonhttp/encoder.go (1)
JSONResponseEncoderWithStatus(64-68)
openmeter/entitlement/access_test.go (1)
openmeter/entitlement/access.go (1)
Access(3-6)
api/client/javascript/src/client/schemas.ts (2)
api/client/go/client.gen.go (2)
CustomerAccess(1679-1683)EntitlementValueWithId(2312-2330)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)
🔇 Additional comments (41)
openmeter/entitlement/utils_test.go (5)
61-67: Good addition of the streaming connector to dependenciesThe addition of the
streamingConnectorfield to the dependencies struct complements the existing fields and follows the same pattern. This will help in properly testing entitlement functionality with streaming capabilities.
95-95: Changed aggregation type from Max to SumThe change from
MeterAggregationMaxtoMeterAggregationSummay impact how meter values are aggregated in tests. This seems intentional to support the new customer access functionality.
117-118: Good initialization of the streaming connector mockThe initialization of the streaming connector using the helper function is clean and follows testing best practices.
119-122: Properly passing the streaming connector to the entitlement registryThe code now uses the initialized streaming connector instance rather than creating a new one inline, which is more maintainable and consistent.
131-137: Complete initialization of dependencies structThe dependencies struct is properly initialized with all required fields, including the new streaming connector. This maintains consistency with the existing pattern.
api/spec/src/entitlements/main.tsp (1)
14-14: Added import for customer.tspThe new import for customer.tsp is correctly added to include the customer access functionality. This is consistent with the PR objective of adding Customer Access API capabilities.
openmeter/customer/httpdriver/handler.go (1)
25-25: Good addition of GetCustomerAccess method to the interfaceThe new
GetCustomerAccessmethod is properly added to the CustomerHandler interface to support the new Customer Access API functionality. This is consistent with the PR objective and follows the existing pattern of handler methods.api/openapi.yaml (3)
2917-2989: New Customer Access Endpoint ImplementationThe new endpoint
/api/v1/customers/{customerIdOrKey}/accessis well-defined. The definition clearly specifies the GET operation with the proper operationId (getCustomerAccess), summary, and description. The parametercustomerIdOrKeyincludes a comprehensive schema with length limits and a regex pattern for input validation. The range of HTTP response codes, each with a dedicated schema reference, ensures robust error handling and clear API communication.
3300-3305: Additional Tag for Subscriptions EndpointThe updated fragment for the
/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint now includes theEntitlementstag along withCustomers. This enhanced tagging should help with logical grouping and filtering in API documentation. Please ensure that the inclusion ofEntitlementsfor subscriptions is intentional and aligns with your overall API categorization strategy.
11591-11605: CustomerAccess Schema DefinitionThe newly added
CustomerAccessschema is structured appropriately. It defines an object with a requiredentitlementsproperty that is designed as a map (usingadditionalProperties) referencingEntitlementValueWithId. Marking it as read-only helps signal that clients should not attempt to modify this field. Overall, this addition aligns well with the API’s goal of encapsulating customer access details.openmeter/entitlement/access.go (1)
2-2:Details
✅ Verification successful
Consider importing necessary packages for EntitlementValue.
The file uses EntitlementValue but doesn't show where it's defined. If EntitlementValue is defined in a different package, make sure to import that package.
Please verify that EntitlementValue is correctly defined elsewhere and is properly accessible in this context. If it's defined in another package, ensure the appropriate import statement is included.
🏁 Script executed:
#!/bin/bash # Look for EntitlementValue definition in the codebase rg 'type EntitlementValue' --type go -A 5Length of output: 3766
Verification Complete: EntitlementValue is Locally Defined
The script output confirms that
EntitlementValueis defined in the codebase (specifically inopenmeter/entitlement/entitlement_types.goas an interface) and is accessible withinopenmeter/entitlement/access.gobecause both files reside in the same package. No additional import is necessary.api/openapi.cloud.yaml (2)
3301-3307: Consistent Tagging for Subscription EndpointIn this hunk, the tags for the
/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint are updated to include both "Entitlements" and "Customers". This ensures consistency and proper categorization across customer-related endpoints.
11716-11729: Robust Definition of the CustomerAccess SchemaThe new
CustomerAccessschema is clearly defined as an object with a requiredentitlementsproperty. Theentitlementsproperty is set up as a map (viaadditionalProperties) linking feature keys toEntitlementValueWithIddefinitions. The inclusion of thereadOnlyattribute and a descriptive comment further clarifies the schema's intent.api/spec/src/cloud/main.tsp (1)
177-181: Addition of Customer interface looks goodThis new interface properly extends the base
OpenMeter.Entitlements.Customerand is tagged with both "Entitlements" and "Customers" which makes sense given its dual role. The route pattern follows the established convention.e2e/productcatalog_test.go (2)
50-50: Good addition of status code assertionAdding an explicit check for the HTTP 201 status code improves the test robustness by verifying the correct response status for customer creation.
721-730: Well structured test for new customer access endpointThe test case properly validates the new customer access functionality by:
- Making a request to get customer access
- Verifying the response status code is correct
- Confirming the response contains entitlements data
- Checking that the expected feature key exists
- Validating the customer has access to the feature
This provides good coverage for the new endpoint functionality.
openmeter/customer/service.go (1)
27-28: Interface methods properly define customer access capabilitiesThe addition of these two methods to the
CustomerServiceinterface is appropriate:
GetEntitlementValueprovides a way to retrieve individual entitlement valuesGetCustomerAccessenables retrieving the complete access information for a customerBoth method signatures follow the established pattern of accepting a context and input parameters, and returning results with potential errors.
openmeter/customer/httpdriver/apimapping.go (2)
8-9: Required imports added correctlyThese imports are necessary for working with the entitlement types and mapping functions used in the new code.
94-116: Thorough implementation of access mapping functionThe
MapAccessToAPIfunction correctly transforms an internalentitlement.Accessobject to the APIapi.CustomerAccessrepresentation. It:
- Creates a map to hold the transformed entitlements
- Iterates through each entitlement in the source object
- Properly maps each entitlement value using the existing helper
- Handles potential errors during mapping
- Constructs API-compatible
EntitlementValueWithIdobjects with all required fields- Returns a properly structured
CustomerAccessobjectThe error handling is appropriate, and all fields are correctly mapped from the internal to the API model.
openmeter/server/server_test.go (2)
722-724: Implementation looks good.The
GetAccessmethod is correctly implemented in theNoopEntitlementConnectorstruct, returning an emptyentitlement.Accessstruct and nil error. This is consistent with the "no-op" pattern used throughout the file for testing purposes.
1021-1023: Implementation looks good.The
GetCustomerAccessmethod is correctly implemented in theNoopCustomerServicestruct, returning an emptyentitlement.Accessstruct and nil error. This aligns with the new API endpoint for retrieving customer access information and matches the pattern used for other no-op implementations.openmeter/customer/service/customer.go (2)
62-65: Error handling improvement looks good.The updated code simplifies the error handling for retrieving subject keys from the customer's usage attribution. Instead of checking lengths and returning a specific error message, it now uses the
GetSubjectKeymethod directly and provides a clearer error message when it fails.
79-91: Implementation of GetCustomerAccess looks good.The method correctly:
- Retrieves the customer using the provided input
- Gets the subject key from the customer's usage attribution
- Handles errors appropriately with clear error messages
- Calls the entitlement connector's GetAccess method with the correct parameters
The implementation follows the same pattern as the existing GetEntitlementValue method and integrates well with the rest of the codebase.
openmeter/server/router/entitlement.go (3)
111-112: Good section header for organization.Adding a clear "Customer APIs" section header helps organize the code and makes it easier to navigate the file.
114-121: Implementation of GetCustomerEntitlementValue looks good.The method correctly routes the request to the customer handler with the appropriate parameters. It follows the established pattern for router methods in this file and properly maps the API parameters to internal structures.
123-129: Implementation of GetCustomerAccess looks good.The method correctly routes the request to the customer handler with the appropriate parameters. It follows the established pattern for router methods in this file and properly integrates with the new API endpoint for retrieving customer access information.
openmeter/entitlement/access_test.go (5)
19-27: Test case for empty access looks good.The test correctly verifies that when no entitlements are found for a subject in a namespace, an empty
Accessstruct is returned. This establishes a baseline behavior for theGetAccessmethod.
29-73: Test case for single entitlement is comprehensive.This test thoroughly validates the behavior for a single entitlement:
- Sets up the necessary test fixtures with controlled time
- Creates a feature and a boolean entitlement
- Advances time to ensure consistent behavior
- Verifies that the returned access contains the correct entitlement
- Checks both the value (has access) and the ID match expectations
The test is well-structured and properly cleans up its resources.
75-123: Test case for multiple entitlements is thorough.This test effectively validates that the system can handle multiple entitlements below the maximum concurrency threshold:
- Creates multiple features and entitlements in a loop
- Tracks the entitlement IDs for verification
- Verifies that all entitlements are present in the returned access
- Checks that each entitlement has the correct access value and ID
The iterative approach with a defined count makes this test both maintainable and comprehensive.
125-220: Test case for multiple entitlement types is robust.This test effectively validates that the system handles different entitlement types correctly:
- Creates boolean, static, and metered entitlements
- Sets up a mock event for the metered entitlement
- Verifies that all three entitlement types are correctly included in the returned access
- Checks that each entitlement has the correct access value
This is a particularly valuable test as it ensures the system works with the full range of entitlement types.
222-270: Test case for high concurrency is important.This test verifies that the system can handle a larger number of entitlements (20) that exceeds typical concurrency thresholds:
- Creates a larger set of features and entitlements
- Ensures all entitlements are correctly returned in the access result
- Validates that each entitlement has the correct access value and ID
This is an important test for ensuring the system's concurrency handling doesn't break under higher loads.
openmeter/entitlement/connector.go (2)
6-11: Validate semaphore usage alignment.The addition of these concurrency packages (
sync,errgroup, andsemaphore) is generally sound. However, please verify that your approach to semaphore acquisition (line 258) aligns properly with thegolang.org/x/sync/semaphoreusage patterns. Some implementations require additional arguments for Acquire.
86-90: Interface expansion.Adding the
GetAccessmethod to theConnectorinterface extends its capabilities. Confirm that all interface implementers now include this method, ensuring no compile-time or runtime issues remain.openmeter/customer/httpdriver/customer.go (2)
357-365: Well-structured request/response types.The introduction of
GetCustomerAccessRequest,GetCustomerAccessResponse, andGetCustomerAccessParamsfollows an established pattern. This maintains clarity and consistency with existing handler definitions.
367-402: Ensure robust test coverage.The
GetCustomerAccesshandler properly synthesizes the request context, calls the service method, and maps entitlements for the response. Please confirm test cases cover edge scenarios (e.g., non-existent customer, empty entitlements, or service-level errors).api/client/javascript/src/client/schemas.ts (4)
3188-3195: Looks good.The
CustomerAccessschema is clearly documented and accurately typed. No issues found.
8799-8799: Export statement is fine.No issues with the new
CustomerAccesstype export; it's consistent with the schema definition.
8851-8852: No concerns here.The
EntitlementValueWithIdexport is correct and aligns well with the newly introduced schema.
13024-13117: Verify error response coverage.The new
getCustomerAccessoperation specifies many possible error responses (400, 401, 403, 404, 412, 500, 503, etc.). Confirm that these response scenarios are tested to ensure robust handling of edge cases and error conditions.Would you like help generating a specialized test suite or opening a new issue to track test coverage for all these errors?
api/spec/src/entitlements/customer.tsp (2)
28-29: Clarify the scope forgetCustomerAccess.
The JSDoc comment states "Get the access of a customer to a given feature (by key)," yet this operation takes no feature key parameter. If it returns access for all features, please revise the doc to avoid confusion.
52-64: Looks good!
ExtendingEntitlementValuewith anidfield inEntitlementValueWithIdis clear and concise.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (11)
api/openapi.yaml (2)
2917-2988: New Customer Access Endpoint Specification
The new/api/v1/customers/{customerIdOrKey}/accessendpoint is defined clearly with the expected parameters, response schema (CustomerAccess), and a comprehensive set of error responses. One suggestion: verify that the endpoint’s description ("Get the access of a customer to a given feature (by key).") accurately reflects whether the API returns the access details for a single feature or a complete map of entitlements.
12942-12986: EntitlementValueWithId Schema Refinement
The extension of the entitlement schema to include anid(along withhasAccessand optional metering properties) fulfills the new model requirements. A minor improvement: there is a typographical error in the description forhasAccess("Shared accross all entitlement types" should be "Shared across all entitlement types"). Consider updating this for clarity and consistency.- description: Whether the subject has access to the feature. Shared accross all entitlement types. + description: Whether the subject has access to the feature. Shared across all entitlement types.api/openapi.cloud.yaml (1)
12963-13006: Definition of EntitlementValueWithId – Minor Typos & ConsistencyThe
EntitlementValueWithIdschema correctly extends the base entitlement model with required fields includinghasAccessandid, along with additional optional properties for metered entitlements. A few minor nitpicks:
- In the
hasAccessproperty description, "accross" should be corrected to "across."- In the
balanceproperty description, consider changing "it's value never turns negative" to "its value never turns negative" for proper possessive usage.- The schema description uses "EntitlementValueWithID" (uppercase “ID”) whereas the schema name is
EntitlementValueWithId; standardize the capitalization for consistency.Below are diff suggestions for clarity:
- description: Whether the subject has access to the feature. Shared accross all entitlement types. + description: Whether the subject has access to the feature. Shared across all entitlement types.- description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from issued grants. Balance represents the remaining balance of the entitlement; its value never turns negative.- description: EntitlementValueWithID extends EntitlementValue with an entitlement ID. + description: EntitlementValueWithId extends EntitlementValue with an entitlement ID.openmeter/entitlement/connector.go (1)
247-249: Consider making maxConcurrency configurableThe hardcoded concurrency limit of 10 could be made configurable through service options or configuration.
Consider moving this to a configuration parameter:
-const maxConcurrency = 10 // TODO: Make this configurable +// Use a field in the connector struct +sem := semaphore.NewWeighted(int64(c.maxConcurrency))Then add the field to the struct and constructor parameters.
openmeter/entitlement/access_test.go (2)
21-21: Fix the spelling of the helper function name.The helper function is named
setupDependecies, which seems like a typographical error. Consider renaming it tosetupDependenciesfor clarity and consistency.-func setupDependecies(t *testing.T) (*Connector, *Dependencies) { +func setupDependencies(t *testing.T) (*Connector, *Dependencies) {Also applies to: 30-30, 76-76, 127-127, 223-223
75-123: Consider stress testing concurrency for added confidence.This sub-test checks multiple entitlements in a loop, but does not actually stress concurrency. Optionally, you could add a goroutine-based test to verify concurrency handling under load.
Would you like an example concurrency test snippet?
openmeter/customer/httpdriver/customer.go (1)
367-402: Enhance error context.When returning errors, consider wrapping them to provide more context, such as:
- return GetCustomerAccessResponse{}, err + return GetCustomerAccessResponse{}, fmt.Errorf("failed to retrieve customer access: %w", err)e2e/productcatalog_test.go (1)
720-730: Add a complementary negative scenario test for broader coverage.This new test confirms a positive path. For a more comprehensive approach, consider adding a test case verifying that a customer without entitlements does not have access. For example:
t.Run("Should fail access for a customer without relevant entitlements", func(t *testing.T) { // Create or use a test customer who lacks subscriptions/entitlements missingEntRes, err := client.GetCustomerAccessWithResponse(ctx, someCustomerWithoutEntitlementsId) require.Nil(t, err) require.Equal(t, http.StatusOK, missingEntRes.StatusCode()) require.NotNil(t, missingEntRes.JSON200) // Ensure the PlanFeatureKey is absent or HasAccess is false require.Nil(t, missingEntRes.JSON200.Entitlements[PlanFeatureKey]) })api/spec/src/entitlements/customer.tsp (1)
10-37: Clarify the comment forgetCustomerAccess.The documentation states "Get the access of a customer to a given feature," yet this endpoint returns all entitlements, not just one feature. Consider updating the summary to reduce confusion:
- * Get the access of a customer to a given feature (by key). + * Get the overall access entitlements of a customer.api/client/javascript/src/client/schemas.ts (2)
604-623: Check docstring for multiple-feature retrieval.The docstring says "Get the access of a customer to a given feature (by key)," but the schema returns a map of entitlements for multiple features. Consider making the docstring clearer or specifying what happens when multiple features are returned.
4176-4212: Fix minor spelling in JSDoc comment.Typo found in the word "accross" at line 4179. Replace with "across" for clarity.
- * @description Whether the subject has access to the feature. Shared accross all entitlement types. + * @description Whether the subject has access to the feature. Shared across all entitlement types.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
api/client/javascript/src/client/schemas.ts(6 hunks)api/openapi.cloud.yaml(4 hunks)api/openapi.yaml(4 hunks)api/spec/src/cloud/main.tsp(1 hunks)api/spec/src/customer.tsp(0 hunks)api/spec/src/entitlements/customer.tsp(1 hunks)api/spec/src/entitlements/main.tsp(1 hunks)e2e/productcatalog_test.go(2 hunks)openmeter/customer/httpdriver/apimapping.go(2 hunks)openmeter/customer/httpdriver/customer.go(1 hunks)openmeter/customer/httpdriver/handler.go(1 hunks)openmeter/customer/service.go(1 hunks)openmeter/customer/service/customer.go(2 hunks)openmeter/entitlement/access.go(1 hunks)openmeter/entitlement/access_test.go(1 hunks)openmeter/entitlement/connector.go(3 hunks)openmeter/entitlement/utils_test.go(4 hunks)openmeter/server/router/customer.go(0 hunks)openmeter/server/router/entitlement.go(2 hunks)openmeter/server/server_test.go(2 hunks)
💤 Files with no reviewable changes (2)
- api/spec/src/customer.tsp
- openmeter/server/router/customer.go
🧰 Additional context used
🧬 Code Definitions (7)
openmeter/customer/service.go (3)
openmeter/customer/customer.go (2)
GetEntitlementValueInput(255-258)GetCustomerInput(212-216)api/api.gen.go (1)
EntitlementValue(2499-2514)api/client/go/client.gen.go (1)
EntitlementValue(2294-2309)
openmeter/entitlement/utils_test.go (4)
openmeter/server/server_test.go (1)
MockStreamingConnector(572-572)openmeter/streaming/testutils/streaming.go (2)
MockStreamingConnector(32-35)NewMockStreamingConnector(19-24)api/api.gen.go (1)
MeterAggregationSum(434-434)openmeter/meter/meter.go (1)
MeterAggregationSum(19-19)
openmeter/customer/httpdriver/apimapping.go (3)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)api/client/go/client.gen.go (2)
CustomerAccess(1679-1683)EntitlementValueWithId(2312-2330)
openmeter/customer/httpdriver/handler.go (1)
openmeter/customer/httpdriver/customer.go (1)
GetCustomerAccessHandler(364-364)
openmeter/customer/httpdriver/customer.go (4)
openmeter/customer/customer.go (2)
GetCustomerInput(212-216)CustomerIDOrKey(109-112)api/api.gen.go (1)
CustomerAccess(1823-1827)openmeter/customer/httpdriver/apimapping.go (1)
MapAccessToAPI(94-116)pkg/framework/commonhttp/encoder.go (1)
JSONResponseEncoderWithStatus(64-68)
api/client/javascript/src/client/schemas.ts (2)
api/client/go/client.gen.go (2)
CustomerAccess(1679-1683)EntitlementValueWithId(2312-2330)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)
openmeter/entitlement/access_test.go (1)
openmeter/entitlement/access.go (1)
Access(3-6)
🔇 Additional comments (41)
api/spec/src/entitlements/main.tsp (1)
14-14: Import looks good, ensures customer functionality is availableAdding the import for
./customer.tspintegrates the customer-related functionality into the entitlements namespace. Based on the PR objectives, this properly connects the newCustomerAccessmodel with the existing entitlements system.openmeter/customer/httpdriver/handler.go (1)
25-25: Addition of GetCustomerAccess is consistent with PR objectivesThe new
GetCustomerAccess() GetCustomerAccessHandlermethod aligns with the PR's goal of introducing customer access API functionality. This interface method declaration correctly follows the pattern of other handler methods in the interface, and matches the handler type defined in the provided code snippet fromcustomer.go.api/openapi.yaml (2)
3300-3306: Subscriptions Endpoint Tag Update
The addition of theEntitlementstag alongsideCustomersfor the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint suggests an intent to relate subscriptions to entitlements. Please confirm that this tagging modification is intentional and consistent with the overall API taxonomy.
11591-11604: CustomerAccess Schema Addition
The newly addedCustomerAccessschema is well defined. It requires theentitlementsproperty, which correctly uses anadditionalPropertiesschema reference toEntitlementValueWithId. This aligns nicely with the design goal to represent customer access through a structured map.api/spec/src/cloud/main.tsp (1)
177-181: Great addition of the Customer interface to enable entitlement access functionality.The new interface is well-structured and follows the existing architectural patterns in the codebase. It correctly extends the base Customer interface from OpenMeter.Entitlements and is appropriately tagged with both "Entitlements" and "Customers", making it discoverable under both categories in the API documentation. The route path follows the RESTful convention for accessing customer-specific resources.
This interface implementation aligns perfectly with the PR objectives of introducing customer access functionality and the
CustomerAccessmodel for defining entitlement access types.api/openapi.cloud.yaml (3)
2918-2990: New "getCustomerAccess" Endpoint SpecificationThe new endpoint for retrieving customer access is clearly defined with a descriptive
operationId, summary, and detailed response sections. The path parametercustomerIdOrKeyincludes robust validation (minLength, maxLength, regex pattern) which is excellent for ensuring proper input. Ensure that downstream client implementations and tests are updated accordingly.
3301-3307: New Subscriptions Endpoint – Incomplete SpecificationThis hunk introduces the
/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint with the appropriate tags. However, the definition appears incomplete (only the beginning of thegetmethod is visible). Please verify that the full specification—such as anoperationId, summary, parameters, and response details—is provided in another part of the spec or will be added soon.
11716-11729: Addition of the CustomerAccess SchemaThe new
CustomerAccessschema is well-defined, requiring anentitlementsproperty that maps feature keys toEntitlementValueWithIdobjects. The description clearly explains the structure and purpose of the data. Consider adding an example value for clarity if your team finds that beneficial in documentation.openmeter/entitlement/access.go (2)
3-6: Well-structured definition of the Access typeThe Access struct properly defines a map that associates feature keys with their corresponding entitlement values and IDs. The comment on line 4 provides clear documentation.
8-11: Clear definition of EntitlementValueWithIdThis struct combines the existing EntitlementValue with an ID field, which aligns with the PR's objective to extend the EntitlementValue model.
openmeter/customer/service.go (1)
27-28: API extension looks goodThe CustomerService interface has been enhanced with:
- The GetEntitlementValue method (retained)
- A new GetCustomerAccess method that returns entitlement.Access
This change aligns with the PR objectives of providing a structured way to represent what features a customer can access.
openmeter/customer/httpdriver/apimapping.go (2)
8-9: Appropriate import statements addedThe imports for entitlement and entitlementdriver packages are necessary for the new functionality.
94-116: Well-implemented mapping functionThe MapAccessToAPI function correctly transforms entitlement.Access to api.CustomerAccess:
- Creates a map for API entitlements
- Properly handles each entitlement value by delegating to entitlementdriver.MapEntitlementValueToAPI
- Includes appropriate error handling
- Correctly maps all required fields (ID, Balance, Usage, Overage, Config, HasAccess)
The implementation preserves the structure defined in the entitlement models.
openmeter/server/server_test.go (2)
722-724: Good test stub implementation for NoopEntitlementConnectorThis implementation of GetAccess for NoopEntitlementConnector returns an empty entitlement.Access and nil error, which is consistent with the pattern of other Noop methods in this test file.
1021-1023: Good test stub implementation for NoopCustomerServiceThe implementation of GetCustomerAccess for NoopCustomerService follows the same pattern as other Noop methods, returning an empty entitlement.Access and nil error.
openmeter/customer/service/customer.go (2)
62-64: Improved error handling with better contextThe code now uses
GetSubjectKey()method to safely retrieve the subject key with better error messaging. This is a cleaner approach than the previous implementation which was checking the array length directly.
79-91: LGTM: Well-structured implementation of GetCustomerAccessThe new method follows the same pattern as
GetEntitlementValue, maintaining consistency in code style. It correctly handles error cases and provides appropriate error context.openmeter/entitlement/utils_test.go (3)
66-66: Appropriate addition of streamingConnector field to dependenciesAdding this field to the test dependencies struct ensures proper test setup and teardown for streaming functionality.
117-118: Consistent streamingConnector instantiation and usageThe code properly initializes the streamingConnector, passes it to the entitlementRegistry, and stores it in the dependencies struct for later use/cleanup.
Also applies to: 121-122, 136-137
95-95:Details
✅ Verification successful
Changed meter aggregation type from Max to Sum
Changing the aggregation type from
MeterAggregationMaxtoMeterAggregationSummay affect test behavior. Ensure this change is intentional and aligns with the expected behavior in production.
🏁 Script executed:
#!/bin/bash # Check where MeterAggregationSum is used in production code rg "MeterAggregationSum" --type go -g "!*_test.go" -A 2 -B 2Length of output: 4766
Verified Aggregation Type Change: Confirmation & Alignment Required
The update from
MeterAggregationMaxtoMeterAggregationSumhas been verified. Our grep search confirms thatMeterAggregationSumis consistently used across the production code (e.g., in files liketest/notification/consumer_balance.go,openmeter/meter/meter.go, and others). This indicates that the change aligns with the intended behavior in production.
- Please ensure that the tests in
openmeter/entitlement/utils_test.gohave been updated to reflect this change.- Double-check that any related test expectations or assertions now correctly account for the aggregation type of SUM.
openmeter/server/router/entitlement.go (4)
7-7: Added required import for customerdriverAppropriate import for the new customer-related handler methods.
111-113: Clear section comment for Customer APIsGood practice to add a section comment to distinguish the customer-specific API endpoints.
116-121: Proper implementation of GetCustomerEntitlementValue handlerThe handler follows the established pattern for routing in the codebase, maintaining consistency with other handler methods.
125-129: Well-defined GetCustomerAccess handlerThe implementation properly delegates to the customer handler and follows the same pattern as other router methods.
openmeter/entitlement/connector.go (6)
6-7: Added imports for concurrency primitivesAppropriate imports for implementing parallel processing in the new
GetAccessmethod.Also applies to: 11-12
87-89: Clear interface definition for GetAccess methodThe method signature and comment clearly describe the purpose and return value of the new method.
231-241: Proper initialization and empty case handlingThe method correctly handles the case where no entitlements are found, returning an empty
Accessobject rather than an error.
243-265: Well-implemented concurrency controlThe code uses appropriate concurrency primitives:
sync.Mapfor thread-safe result collectionerrgroupfor coordinated error handlingsemaphoreto limit concurrency to 10 parallel operationsThis approach will prevent overwhelming the system while still providing performance benefits.
267-277: Efficient entitlement value retrieval and storageThe goroutine efficiently retrieves the entitlement value and correctly stores it with the entitlement ID in the result map.
287-315: Thorough type checking when converting resultsThe code carefully converts from
sync.Mapto a regular map with comprehensive type assertion checks, ensuring type safety.openmeter/entitlement/access_test.go (4)
19-27: Test coverage looks good for the empty entitlements scenario.
No issues found; this sub-test verifies the "no entitlements" logic correctly.
29-73: Single entitlement sub-test is well-structured.
The logic to create a single feature and entitlement, then check access is clear and correct.
125-220: Well-structured coverage for multiple entitlement types.
Boolean, static, and metered entitlements are all tested thoroughly and validated.
222-270: High concurrency entitlement test is clear.
The approach to create 20 entitlements then verify them is robust.openmeter/customer/httpdriver/customer.go (1)
359-364: New type definitions appear consistent with existing patterns.
Naming and struct usage follow the established handler approach; no issues found.e2e/productcatalog_test.go (1)
50-50: Great assertion for verifying successful customer creation.
This ensures the response code is correct and yields immediate feedback on failures.api/spec/src/entitlements/customer.tsp (1)
39-65: Models forCustomerAccessandEntitlementValueWithIdare well-designed.
They extend existing logic to include an entitlement ID and mirror the underlying data requirements accurately.api/client/javascript/src/client/schemas.ts (4)
3188-3195: Schema definitions look consistent.The
CustomerAccessschema and theentitlementsproperty appear to be well-defined for storing multipleEntitlementValueWithIdobjects. No issues identified here.
8799-8799: Export reference is clear.Exporting this type (
CustomerAccess) ensures consistency with the corresponding schema. Looks good.
8851-8852: No issues with type export.Exporting
EntitlementValueWithIdis straightforward and aligned with the new schema definitions.
13024-13117: Confirm complete test coverage and consider clarifying non-happy-path scenarios.The
getCustomerAccessoperation defines multiple error responses (400, 401, 403, etc.). Ensure these conditions are tested (e.g., unauthorized requests, invalid paths). Additionally, verify whether a 429 (rate limit) status should be included if applicable in the broader system.
4c071dd to
547890f
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (11)
api/openapi.yaml (4)
2917-2989: New Customer Access Endpoint Definition is Well Structured
The new endpoint/api/v1/customers/{customerIdOrKey}/accessis defined clearly with an appropriate operationId (getCustomerAccess), detailed parameter constraints, and a comprehensive set of response definitions. All HTTP status responses are documented with proper references to existing schemas.
**
** Consider providing example responses (using theexampleproperty) in the response schemas to further aid API consumers.
3300-3306: Consistent Tag Assignment for Subscriptions Endpoint
The update to the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint shows that the tags have been updated to include both "Entitlements" and "Customers", which promotes consistency across similar endpoints.
**
** Verify that the logical grouping via these tags meets the overall API design; if additional context is needed on this endpoint, consider adding a summary or description.
11558-11572: CustomerAccess Schema Definition is Clear and Concise
The newCustomerAccessschema is implemented correctly as an object requiring theentitlementsproperty. The use ofadditionalPropertiesreferring toEntitlementValueWithIdis consistent with the intent of mapping feature keys to their entitlement details. ThereadOnly: trueattribute reinforces that this data is output only.
**
** You might consider adding an example for theCustomerAccessobject to show expected key–value pairs.
12912-12952: EntitlementValueWithId Schema Defined with Minor Inconsistency in Naming
This new schema extends entitlement details by including anidfield along with other optional properties such asbalance,usage,overage, andconfig. The required fields (hasAccessandid) are correctly enforced, and the descriptions are thorough.
However, note that the description on line 12952 refers to "EntitlementValueWithID" with a capitalized "ID," while the schema name isEntitlementValueWithId. For consistency and clarity, update the description to match the schema name.
**
Below is a proposed diff to address the naming consistency:- description: EntitlementValueWithID extends EntitlementValue with an entitlement ID. + description: EntitlementValueWithId extends EntitlementValue with an entitlement ID.api/openapi.cloud.yaml (1)
12933-12973: Schema Enhancement: EntitlementValueWithId Definition ImprovementsThe new
EntitlementValueWithIdschema meets the design goals by extending entitlement details with an ID. A few minor suggestions:
- In the description for
hasAccess(line 12941), correct the typo "accross" to "across".- In the
balanceproperty's description (line 12947), change "it's value never turns negative" to "its value never turns negative".- Ensure naming consistency by using "EntitlementValueWithId" (not "WithID") uniformly in both the title and description.
These refinements will help maintain clarity and professional documentation.
openmeter/entitlement/connector.go (1)
248-249: Consider making the concurrency limit configurableThe code currently uses a hard-coded concurrency limit of 10, with a TODO to make it configurable.
Consider implementing this configuration option soon, as the appropriate concurrency limit may vary based on deployment environment, system resources, and expected load. This could be handled through:
- const maxConcurrency = 10 // TODO: Make this configurable + // Get concurrency limit from configuration with reasonable default + maxConcurrency := c.config.GetAccessMaxConcurrency + if maxConcurrency <= 0 { + maxConcurrency = 10 + }api/client/javascript/src/client/schemas.ts (2)
4179-4179: Fix typo in property descriptionThere's a spelling error in the description text.
- * @description Whether the subject has access to the feature. Shared accross all entitlement types. + * @description Whether the subject has access to the feature. Shared across all entitlement types.
4206-4211: Remove redundant description in id field documentationThe
idfield has both a standalone description line and a@descriptiontag that contain the same text.- /** - * The entitlement ID - * @description The entitlement ID. - * @example 01G65Z755AFWAKHE12NY0CQ9FH - */ + /** + * @description The entitlement ID. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */openmeter/entitlement/access_test.go (2)
21-27: Fix typo in helper function naming.In the subtest "Should return empty access," the helper function is named
setupDependecies(t), which appears to be a misspelling of “setupDependencies.”Apply this diff to correct the function name:
- conn, deps := setupDependecies(t) + conn, deps := setupDependencies(t)
125-220: Comprehensive test covering multiple entitlement types.This subtest validates boolean, static, and metered entitlements. The approach of mocking time and events to trigger usage is sound. Suggest verifying negative scenarios (e.g., configuration errors) in future tests.
openmeter/customer/httpdriver/customer.go (1)
367-402: Handler implementation aligns with project conventions.• The function correctly resolves namespaces, constructs the request, and applies the standard error handling pattern.
•MapAccessToAPIusage is consistent with similar mapping functions in this file.
• Consider adding an explicit check fornilreturn values from the service to handle not-found scenarios more gracefully (like done in other handlers).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
api/client/javascript/src/client/schemas.ts(6 hunks)api/openapi.cloud.yaml(4 hunks)api/openapi.yaml(4 hunks)api/spec/src/cloud/main.tsp(1 hunks)api/spec/src/customer.tsp(0 hunks)api/spec/src/entitlements/customer.tsp(1 hunks)api/spec/src/entitlements/main.tsp(1 hunks)e2e/productcatalog_test.go(2 hunks)openmeter/customer/httpdriver/apimapping.go(2 hunks)openmeter/customer/httpdriver/customer.go(1 hunks)openmeter/customer/httpdriver/handler.go(1 hunks)openmeter/customer/service.go(1 hunks)openmeter/customer/service/customer.go(2 hunks)openmeter/entitlement/access.go(1 hunks)openmeter/entitlement/access_test.go(1 hunks)openmeter/entitlement/connector.go(3 hunks)openmeter/entitlement/utils_test.go(4 hunks)openmeter/server/router/customer.go(0 hunks)openmeter/server/router/entitlement.go(2 hunks)openmeter/server/server_test.go(2 hunks)
💤 Files with no reviewable changes (2)
- api/spec/src/customer.tsp
- openmeter/server/router/customer.go
🚧 Files skipped from review as they are similar to previous changes (7)
- api/spec/src/entitlements/main.tsp
- openmeter/customer/httpdriver/handler.go
- api/spec/src/cloud/main.tsp
- openmeter/entitlement/access.go
- openmeter/customer/service.go
- e2e/productcatalog_test.go
- openmeter/entitlement/utils_test.go
🧰 Additional context used
🧬 Code Definitions (6)
openmeter/customer/httpdriver/apimapping.go (3)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)api/client/go/client.gen.go (2)
CustomerAccess(1679-1683)EntitlementValueWithId(2312-2330)
openmeter/customer/service/customer.go (4)
pkg/models/error.go (1)
NewGenericConflictError(68-70)openmeter/customer/service/service.go (1)
Service(13-18)openmeter/customer/customer.go (1)
GetCustomerInput(212-216)openmeter/entitlement/access.go (1)
Access(3-6)
openmeter/entitlement/connector.go (3)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (1)
EntitlementValueWithId(2517-2535)api/client/go/client.gen.go (1)
EntitlementValueWithId(2312-2330)
openmeter/entitlement/access_test.go (1)
openmeter/entitlement/access.go (1)
Access(3-6)
api/client/javascript/src/client/schemas.ts (2)
api/client/go/client.gen.go (2)
CustomerAccess(1679-1683)EntitlementValueWithId(2312-2330)api/api.gen.go (2)
CustomerAccess(1823-1827)EntitlementValueWithId(2517-2535)
openmeter/customer/httpdriver/customer.go (4)
openmeter/customer/customer.go (2)
GetCustomerInput(212-216)CustomerIDOrKey(109-112)api/api.gen.go (1)
CustomerAccess(1823-1827)openmeter/customer/httpdriver/apimapping.go (1)
MapAccessToAPI(94-116)pkg/framework/commonhttp/encoder.go (1)
JSONResponseEncoderWithStatus(64-68)
🔇 Additional comments (25)
openmeter/customer/httpdriver/apimapping.go (2)
8-9: Appropriate imports added for the new functionalityThe addition of imports for the entitlement package and entitlementdriver is necessary to support the new mapping function.
94-116: Well-structured implementation ofMapAccessToAPIThe function correctly maps an
entitlement.Accessobject to anapi.CustomerAccessobject, following the established mapping patterns in the codebase. It properly handles each field of the entitlement value and includes appropriate error handling.The implementation is clean, concise, and consistent with other mapping functions in the file.
openmeter/server/server_test.go (2)
722-724: Appropriate implementation ofGetAccessfor test mockThe
GetAccessmethod is appropriately implemented for theNoopEntitlementConnectormock, returning empty values consistent with the "noop" pattern used throughout the test file.
1021-1023: Correct implementation ofGetCustomerAccessfor test mockThe
GetCustomerAccessmethod is correctly implemented for theNoopCustomerServicemock, providing the necessary method signature to support testing the new customer access functionality.openmeter/customer/service/customer.go (2)
118-120: Improved subject key retrieval and error handlingThe refactoring from manual subject key validation to using the dedicated
GetSubjectKey()method improves code clarity and maintainability. The error message is now more specific, which will help with debugging when subject key retrieval fails.
135-147: Well-implemented customer access retrieval methodThe new
GetCustomerAccessmethod follows a consistent pattern with other service methods. It properly handles errors at each step and returns a structuredentitlement.Accessobject as required by the PR objectives. The method effectively reuses existing code paths (GetCustomerand subject key retrieval) before fetching access information through the entitlement connector.api/openapi.cloud.yaml (3)
2918-2990: New Endpoint Definition: Validate Customer Access SpecificationThe new
/api/v1/customers/{customerIdOrKey}/accessendpoint is well-defined with a clear operation ID, summary, and detailed responses. The parameter validation (including min/max length and the custom regex on line 2931) appears designed to cover both common ID formats and a specific format for entitlement IDs. Please verify that the regex handles all intended edge cases and that client applications are aware of the new endpoint.
3301-3307: Consistent Tag Application for Subscription EndpointThe modifications extending the unexpected problem schema and the inclusion of the
"Entitlements"and"Customers"tags for the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint ensure consistent grouping with other endpoints. Verify that this tag ordering aligns with the overall API design and documentation.
11683-11697: New CustomerAccess Schema: Correct Structure and UsageThe
CustomerAccessschema is introduced as an object with a required propertyentitlements. UsingadditionalPropertiesto referenceEntitlementValueWithIdeffectively models a dictionary of feature keys to entitlement objects. Please ensure that this schema is consistently applied in the API responses for the new endpoint.openmeter/server/router/entitlement.go (1)
111-130: Well-structured implementation of customer API endpointsThe new API endpoints for customer entitlement value and access follow the established pattern in the codebase. The implementation correctly integrates with the existing router structure and follows Go best practices for HTTP handlers.
openmeter/entitlement/connector.go (4)
87-89: Good documentation for the new interface methodThe documentation clearly explains the purpose of the
GetAccessmethod and its return value. This maintains the code's readability and helps future developers understand the method's intention.
231-241: LGTM - Initial error handling and early returnsThe implementation starts with appropriate error handling and includes an early return for the case where no entitlements are found, which is an efficient approach.
243-285: Well-implemented concurrent processing with proper error handlingThe concurrent processing of entitlements is well-implemented using Go's concurrency primitives (
errgroup,semaphore). The code:
- Properly limits concurrent operations (preventing resource exhaustion)
- Creates local copies of variables for goroutines (avoiding closure issues)
- Handles errors appropriately at each step
287-315: Thorough error handling during map conversionThe implementation properly handles potential type assertion errors when converting from
sync.Mapto a regular map. The detailed error messages will be helpful for debugging any unexpected issues.api/client/javascript/src/client/schemas.ts (5)
604-623: New endpoint for customer access looks goodThis addition defines a new GET endpoint at
/api/v1/customers/{customerIdOrKey}/accessto retrieve customer access information, which aligns with the PR objective of introducing customer access APIs.
3188-3195: New CustomerAccess schema implementation looks goodThe schema properly defines a map of entitlements where feature keys are mapped to their corresponding entitlement values and IDs, which matches the PR description.
4176-4212: EntitlementValueWithId schema implementation looks goodThis schema extends EntitlementValue with an ID field as described in the PR objectives, and includes comprehensive property descriptions with examples.
8799-8799: Type exports look goodThe type exports for
CustomerAccessandEntitlementValueWithIdare properly defined, making them available for use in the client code.Also applies to: 8851-8852
13024-13117: Operation definition for getCustomerAccess is comprehensiveThe operation definition includes all necessary parameters and a complete set of response types for various HTTP status codes, which is excellent for proper error handling.
openmeter/entitlement/access_test.go (3)
29-73: Good coverage for a single entitlement scenario.This test thoroughly verifies that a single boolean entitlement is reflected in the retrieved access. The usage of
require.NoErrorandrequire.Equalensures correctness. No changes needed.
75-123: Effective test for multiple entitlements.The loop-based creation of multiple entitlements (< max concurrency) is a good approach to ensure each is retrieved. The checks for IDs and
HasAccess()are consistent. No changes needed.
222-270: Good stress test for higher concurrency.The test with 20 entitlements is a valid approach to ensure the method handles larger volumes without issues. The transitional time updates are beneficial. Looks good overall.
openmeter/customer/httpdriver/customer.go (1)
358-365: New types for customer access retrieval look consistent.Defining
GetCustomerAccessRequest,GetCustomerAccessResponse, andGetCustomerAccessParamsaligns well with the existing pattern for typed request/response structs.api/spec/src/entitlements/customer.tsp (2)
10-37: Interface definition follows a clear REST pattern.The
@route,@operationId, and parameters (customerIdOrKey,featureKey) are well-declared. The summary annotations are concise.
39-65: Models structurally align with the entitlement concept.•
CustomerAccessmodel provides a clear record of featureKey →EntitlementValueWithId.
•EntitlementValueWithIdextends the base value with anidfield, allowing precise tracking.
• Summaries and friendlyName decorators improve API documentation.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
api/spec/src/entitlements/customer.tsp (3)
17-25: Consider clarifying the usage of the optionaltimeparameter.It's not fully clear whether it represents a historical or future time for entitlement values. Including a short description of how
timeinfluences the entitlement lookup would help mitigat confusion.
30-36: Consider supporting a future or past access lookup.The new
getCustomerAccessoperation returns the current access. If you need time-based entitlements, consider adding an optionaltimeparameter, similar togetCustomerEntitlementValue, for better consistency in retrieving access at a specific point in time.
48-49: Validate key usage in the entitlements record.
entitlements: Record<EntitlementValueWithId>assumes string keys by default. Ensure that feature keys won't conflict with any other naming conventions or special characters. If you need more constraints (e.g., length, allowed characters), consider a typedRecord<Key, EntitlementValueWithId>.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
api/spec/src/entitlements/customer.tsp(1 hunks)e2e/productcatalog_test.go(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- e2e/productcatalog_test.go
🔇 Additional comments (1)
api/spec/src/entitlements/customer.tsp (1)
57-63: All set for the extended entitlement model.The extension of
EntitlementValuewith anidproperty is concise and clear. Ensure thatglobal.ULIDis consistent with your domain requirements for unique identifiers.
e3c574c to
809111e
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (8)
api/openapi.cloud.yaml (4)
2918-2990: New Endpoint for Customer Access Retrieval
The new/api/v1/customers/{customerIdOrKey}/accessendpoint is clearly defined with a well-structured GET operation. The path parametercustomerIdOrKeyis constrained appropriately withminLength,maxLength, and a regular expression pattern. However, the operation’s description ("Get the access of a customer to a given feature (by key)") might be a bit misleading because there is no explicit feature key parameter in the endpoint. If the intent is to return all entitlements mapped by feature keys, it might be clearer to state that in the description.
3301-3307: Consistent Tagging for Subscriptions Endpoint
In this hunk, the addition of theEntitlementstag alongsideCustomersfor the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint improves consistency and categorization of API endpoints. Just double-check that this tag association aligns with the overall API grouping strategy.
11647-11660: Definition of CustomerAccess Schema
The newly introducedCustomerAccessschema is well-defined. It mandates theentitlementsproperty, which correctly maps feature keys to entitlement values (using theEntitlementValueWithIdschema). The schema is read-only and includes a clear description, making its intention transparent. Consider adding an example for further clarity.
12917-12957: Definition of EntitlementValueWithId Schema
TheEntitlementValueWithIdschema is comprehensive and clearly outlines the properties, including required fieldshasAccessandid, as well as optional ones likebalance,usage,overage, andconfig.
- Minor Typo: In the description for
hasAccess, "Shared accross all entitlement types" should be corrected to "Shared across all entitlement types".
Overall, the schema clearly extendsEntitlementValueby adding the entitlement ID and adhering to the documented format.openmeter/entitlement/connector.go (2)
248-249: Consider making maxConcurrency configurableThe TODO comment suggests making the concurrency limit configurable, which is a good improvement for future work.
Consider implementing this as a configuration option that can be passed to the connector constructor or set as an environment variable, allowing for tuning based on the deployment environment.
259-260: Improve error message clarityThe comment "Ctx canceled or never rly happens, but critical if does" could be clearer.
- // Ctx canceled or never rly happens, but critical if does + // Context was either canceled or there was a critical semaphore acquisition errorapi/openapi.yaml (2)
2917-2989: Clarify Endpoint Functionality and Parameter UsageThe new endpoint
/api/v1/customers/{customerIdOrKey}/accessis well defined with a clear operationId, comprehensive responses, and proper parameter validation. However, the description ("Get the access of a customer to a given feature (by key).") may imply that a specific feature key is expected, yet no separate feature key parameter is provided. Please verify whether the intent is to return the entire set of entitlements or if a feature key filter is missing from the endpoint definition.
12894-12937: New EntitlementValueWithId Schema – Minor Typos and Naming ConsistencyThe
EntitlementValueWithIdschema is comprehensively defined with detailed properties such ashasAccess,balance,usage,overage,config, andid. The use ofreadOnly: truefor read-only fields is appropriate.
- Typo: In the description for
hasAccess(line 12905), "accross" should be corrected to "across".- Naming Consistency: The title in line 12936 uses "The entitlement ID" and the description in line 12937 refers to "EntitlementValueWithID" (with "ID" in all caps). It is advisable to consistently use either "Id" or "ID" across the schema and its references.
Below is a suggested diff for these adjustments:
@@ -12904,6 +12904,6 @@ hasAccess: type: boolean - description: Whether the subject has access to the feature. Shared accross all entitlement types. + description: Whether the subject has access to the feature. Shared across all entitlement types. example: true readOnly: true @@ -12935,4 +12935,4 @@ id: type: string pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ - description: The entitlement ID. + description: The entitlement id. @@ -12936,3 +12936,3 @@ - title: The entitlement ID + title: The entitlement id
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
api/client/javascript/src/client/schemas.ts(6 hunks)api/openapi.cloud.yaml(4 hunks)api/openapi.yaml(4 hunks)api/spec/src/cloud/main.tsp(1 hunks)api/spec/src/customer.tsp(0 hunks)api/spec/src/entitlements/customer.tsp(1 hunks)api/spec/src/entitlements/main.tsp(1 hunks)e2e/productcatalog_test.go(3 hunks)openmeter/customer/httpdriver/apimapping.go(2 hunks)openmeter/customer/httpdriver/customer.go(1 hunks)openmeter/customer/httpdriver/handler.go(1 hunks)openmeter/customer/service.go(1 hunks)openmeter/customer/service/customer.go(2 hunks)openmeter/entitlement/access.go(1 hunks)openmeter/entitlement/access_test.go(1 hunks)openmeter/entitlement/connector.go(3 hunks)openmeter/entitlement/utils_test.go(4 hunks)openmeter/server/router/customer.go(0 hunks)openmeter/server/router/entitlement.go(2 hunks)openmeter/server/server_test.go(2 hunks)
💤 Files with no reviewable changes (2)
- api/spec/src/customer.tsp
- openmeter/server/router/customer.go
🚧 Files skipped from review as they are similar to previous changes (7)
- api/spec/src/entitlements/main.tsp
- openmeter/customer/httpdriver/handler.go
- api/spec/src/cloud/main.tsp
- openmeter/entitlement/utils_test.go
- openmeter/customer/service.go
- openmeter/entitlement/access_test.go
- openmeter/entitlement/access.go
🧰 Additional context used
🧬 Code Definitions (5)
openmeter/server/server_test.go (2)
openmeter/entitlement/access.go (1)
Access(3-6)openmeter/customer/customer.go (1)
GetCustomerInput(212-216)
openmeter/customer/service/customer.go (4)
pkg/models/error.go (1)
NewGenericConflictError(68-70)openmeter/customer/service/service.go (1)
Service(13-18)openmeter/customer/customer.go (1)
GetCustomerInput(212-216)openmeter/entitlement/access.go (1)
Access(3-6)
openmeter/customer/httpdriver/apimapping.go (3)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (2)
CustomerAccess(1791-1795)EntitlementValueWithId(2501-2519)api/client/go/client.gen.go (2)
CustomerAccess(1656-1660)EntitlementValueWithId(2305-2323)
openmeter/entitlement/connector.go (3)
openmeter/entitlement/access.go (2)
Access(3-6)EntitlementValueWithId(8-11)api/api.gen.go (1)
EntitlementValueWithId(2501-2519)api/client/go/client.gen.go (1)
EntitlementValueWithId(2305-2323)
openmeter/customer/httpdriver/customer.go (4)
openmeter/customer/customer.go (2)
GetCustomerInput(212-216)CustomerIDOrKey(109-112)api/api.gen.go (1)
CustomerAccess(1791-1795)openmeter/customer/httpdriver/apimapping.go (1)
MapAccessToAPI(94-116)pkg/framework/commonhttp/encoder.go (1)
JSONResponseEncoderWithStatus(64-68)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (30)
openmeter/customer/httpdriver/apimapping.go (2)
8-9: Imports look appropriate.
These newly added imports are consistent with the subsequent usage ofentitlementandentitlementdriver.
93-116: MapAccessToAPI function appears correctly implemented.
This function neatly transforms raw entitlements into the API structure. Handling of the mapping error with an early return ensures robust error propagation. Ifaccess.Entitlementsmight be nil in some edge cases, confirm that returning an empty map is desired behavior. Otherwise, no issues found.openmeter/server/server_test.go (2)
725-727: No-op implementation is consistent with naming.
This method properly satisfies theGetAccessinterface by returning a defaultentitlement.Accesswith no side effects.
1024-1026: No-op GetCustomerAccess implementation.
This stub method matches the pattern seen in other no-op services, returning a default access object. If future tests require actual logic, consider a test double that returns non-empty data.openmeter/customer/service/customer.go (2)
118-120: Error handling for subject key retrieval is clear.
This change ensures a conflict error is raised when the usage attribution subject key is unavailable, improving error transparency.
135-147: GetCustomerAccess logic is well-structured.
Fetching the customer, then deriving the subject key before retrieving entitlements is a logical flow. Ensure tests cover whenUsageAttributionis missing a valid subject key. Otherwise, looks good.openmeter/server/router/entitlement.go (1)
111-130: LGTM: Well-structured API handlers for customer accessThe new handlers follow the established pattern of the codebase and are properly documented with clear comments indicating their purpose and API endpoint paths.
These endpoints provide a clean separation between customer-specific APIs and subject-related endpoints, which enhances the organization of the API surface.
openmeter/entitlement/connector.go (5)
87-89: Interface addition looks goodThe new method is well-documented with clear comments explaining its purpose and return values.
231-242: Good error handling and early return patternThe implementation properly checks for errors when retrieving entitlements and returns early with an empty Access object when no entitlements are found, avoiding unnecessary processing.
243-285: Well-implemented concurrency patternThe concurrent implementation using errgroup and semaphore is excellent for performance while maintaining controlled resource usage. The code correctly:
- Uses sync.Map for thread-safe storage
- Creates local copies of variables for goroutines
- Limits concurrency with a semaphore
- Properly handles context cancellation
- Waits for all goroutines to complete
This will provide efficient parallel retrieval of entitlement values.
287-315: Good type safety in map conversionThe conversion from sync.Map to a regular map with thorough type assertion checks is an excellent defensive programming practice. The error handling for unexpected types provides good diagnostics if something goes wrong.
231-315:Details
❓ Verification inconclusive
Consider behavior for partial failures
Currently, if any single entitlement value retrieval fails, the entire operation fails. Depending on your requirements, you might want to consider allowing partial results.
Is it acceptable to return partial results if some entitlement value retrievals fail? Or is the current all-or-nothing approach the desired behavior?
🌐 Web query:
What are best practices for handling partial failures in concurrent API operations?💡 Result:
Handling partial failures in concurrent API operations requires robust strategies to ensure system reliability and graceful degradation. Here are the key best practices:
Allow Partial Success in Bulk Operations
Enable APIs to process successful portions of bulk requests even when some elements fail. This prevents full operation rollbacks for minor errors. Implement
partialSuccessflags in requests where feasible[1]. For example:POST /bulk-update?partialSuccess=trueImplement Idempotency and Request Deduplication
Use Idempotency-Key headers to ensure retries don't cause duplicate processing. Services should temporarily store request hashes (24+ hours) to detect and prevent replay attacks[7].
Strategy Implementation Benefit Client-generated UUID Idempotency-Key: 7da7a728-f910-11e6-942a-68f728c1ba70Prevents duplicate execution Request hash validation SHA-256 hash of payload + headers Detects modified retries Use Intelligent Retry Mechanisms
- Exponential backoff with jitter: Initial 1s delay, doubling each attempt with ±30% randomization[3][9]
- Circuit breakers: Trip after 5 consecutive failures, enter half-open state after 60s[3][6]
- Retry budgets: Limit to 3 attempts for non-idempotent operations[4]
Retry decision flow:
if error.is_transient() and retries < MAX_RETRIES: wait_time = min(base_delay * 2**retries + random_jitter, MAX_DELAY) retry_after(wait_time)Isolate Concurrent Errors
Handle failures per-request using:
Promise.allSettled(requests).then(results => { results.forEach((result, index) => { if (result.status === 'rejected') { logError(`Request ${index} failed: ${result.reason}`); } }); });This prevents single failures from blocking entire batches[2][8].
Implement Compensating Transactions
For multi-service operations, use sagas pattern with rollback handlers:
def process_order begin reserve_stock() charge_card() rescue => e refund_card() if card_charged? restore_stock() if stock_reserved? raise e end endMaintain atomicity through reverse operations[5][6].
Optimize Concurrency Controls
Align parallel execution with API limits using:
API Capacity Concurrency Page Size Retry Delay Strict limits 5 threads 50-100 5-10s High capacity 20 threads 1000+ 1-2s Monitor metrics like 95th percentile latency and error recurrence rate[4][10].
Provide Structured Error Responses
Adhere to RFC 9457 standards:
{ "type": "https://api.example/errors/rate-limit", "title": "Rate Limit Exceeded", "status": 429, "detail": "100 requests/hour exceeded", "instance": "/orders/123", "retry_after": 3600 }Include machine-readable codes and human guidance[4][7].
Asynchronous Processing Patterns
For long-running operations:
- Return
202 Acceptedwith status endpoint- Implement webhooks for completion notifications
- Store results in cloud storage for large payloads[3][10]
Combine these strategies with monitoring for error rates (>5% alerting) and automated retry queues to create resilient systems. Regular load testing under failure conditions helps validate implementation effectiveness[9][10].
Citations:
- 1: https://www.smartsheet.com/content-center/best-practices/tips-tricks/api-best-practices
- 2: https://app.studyraid.com/en/read/11516/361785/error-handling-in-concurrent-requests
- 3: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/partial-failure-strategies
- 4: https://zuplo.com/blog/2025/02/11/best-practices-for-api-error-handling
- 5: https://thoughtbot.com/blog/handling-external-api-errors-a-transactional-approach
- 6: https://www.sayonetech.com/blog/how-handle-failed-transactions-microservices/
- 7: https://schweizerischebundesbahnen.github.io/api-principles/restful/best-practices/
- 8: http://joeduffyblog.com/2009/06/23/concurrency-and-exceptions/
- 9: https://softwarecountry.com/company/our-blog/fault-handling-in-dotnet/
- 10: https://www.celigo.com/blog/concurrency-best-practices-for-large-data-volumes/
Action Required: Revisit Partial Failure Handling Strategy in
GetAccessThe current implementation returns an error upon the first failure in retrieving an entitlement value, effectively enforcing an all-or-nothing outcome. However, industry best practices for handling concurrent API operations suggest that allowing partial success can significantly enhance system resilience. For bulk operations—especially when individual entitlement retrievals are independent—it is often preferable to accumulate successful responses and report or log failures separately.
Points for Consideration:
- Partial Aggregation: Evaluate if it’s acceptable to return the successfully retrieved entitlement values even when a subset of them fail.
- Error Reporting: Consider aggregating individual errors (e.g., using error slices or multi-error types) instead of aborting the entire operation immediately.
- System Requirements: Align the decision with your API’s SLAs and client expectations. If consistent full results are needed, the current approach may be justified; otherwise, a partial-success strategy might be more user-friendly.
Please verify if shifting to a partial-success model is acceptable for your use case or if maintaining the current all-or-nothing approach is the desired behavior.
api/client/javascript/src/client/schemas.ts (7)
604-623: New endpoint for customer access API looks goodThis code introduces a new API endpoint for retrieving customer access information, which aligns with the PR objectives.
608-608: Path parameter definition inconsistencyThe endpoint path definition has
path?: neverwhich contradicts the operation definition that requires acustomerIdOrKeypath parameter in lines 13238-13240.- path?: never + path: { + customerIdOrKey: string + }
3139-3146: CustomerAccess schema definition is well-structuredThe schema provides a clear description of how customer feature access is represented, with entitlements being a map of feature keys to their corresponding entitlement values and IDs.
4141-4177: EntitlementValueWithId schema provides comprehensive access informationThis schema successfully extends EntitlementValue by adding the entitlement ID property, while maintaining all the necessary fields for representing entitlement access details. The documentation is thorough with clear descriptions and examples for each property.
8993-8993: Type export for CustomerAccess is correctly definedThe type export properly references the corresponding schema definition.
9046-9047: Type export for EntitlementValueWithId is correctly definedThe type export properly references the corresponding schema definition.
13234-13327: getCustomerAccess operation is well-defined with comprehensive response typesThe operation definition includes the required path parameter and all possible response types with appropriate status codes and content types. The thorough definition of response types will help with proper error handling on the client side.
api/openapi.yaml (2)
3300-3306: Consistent Tagging for EndpointsThe changes in this hunk update the tags for the subscriptions endpoint, adding both "Entitlements" and "Customers". This is consistent with the new access endpoint grouping. Just ensure that these tags align with the overall API categorization strategy.
11522-11538: New CustomerAccess Schema DefinitionThe
CustomerAccessschema is introduced clearly with a required propertyentitlements, which is defined as an object mapping feature keys toEntitlementValueWithIdobjects. The schema description and read-only setting help to convey its intended immutability. Verify that downstream consumers and API documentation reflect this structure.openmeter/customer/httpdriver/customer.go (2)
359-365: Good addition of request/response types for customer access.The new type definitions correctly map to existing patterns for request and response structures in this file. Their naming and usage appear consistent with other handlers.
367-402:Details
❓ Verification inconclusive
Confirm handling of not-found cases.
While this handler properly forwards errors from
h.service.GetCustomerAccessto the caller, consider verifying if the service layer returns a specific “not found” error for missing customers and whether this handler’s error handling transforms it into an HTTP 404.Please run the following script to locate where
GetCustomerAccesserrors might be mapped to HTTP 404 or analogous responses:
🏁 Script executed:
#!/bin/bash # Description: Verify the error mapping from the service layer to the HTTP layer for GetCustomerAccess rg -A 10 "func (.*)GetCustomerAccess"Length of output: 8360
Review Error Handling for Not-Found Cases in GetCustomerAccess
It appears that the
GetCustomerAccesshandler inopenmeter/customer/httpdriver/customer.goforwards errors directly from the service layer without explicitly mapping "not found" scenarios to an HTTP 404 response. In the service implementation (openmeter/customer/service/customer.go), errors (including potential not-found errors froms.GetCustomer) are returned as-is, and there is no clear evidence in the current code or in global middleware (based on our grep results) that these errors are being converted into 404 responses.Please verify the following:
- Service Layer Behavior: Confirm if
h.service.GetCustomerAccessreturns a specific error type (or value) for missing customers.- Error Mapping: Check if a global error handler or middleware is responsible for converting these errors to an HTTP 404 response. If not, consider adding explicit handling in the HTTP handler.
- Documentation: If the error transformation is managed externally, please document this behavior to ensure clarity for future maintenance.
e2e/productcatalog_test.go (3)
50-50: Great addition of the status code check after creating a customer.Ensuring the response is
201helps confirm correct resource creation and eliminates silent failures.
75-83: Helpful negative test case for empty access.This test scenario ensures that a customer with no entitlements is handled gracefully, returning an empty map. It looks complete and effectively confirms the new endpoint’s expected behavior.
779-789: Positive test case validates feature entitlement.This test confirms that a subscribed feature key is indeed present and accessible in the returned entitlements. It’s consistent and enhances coverage for the newly introduced endpoint.
api/spec/src/entitlements/customer.tsp (4)
1-9: Imports and namespace definitions look good.The imported libraries and the
OpenMeter.Entitlementsnamespace are consistent with the rest of the codebase, aligning with similar usage found elsewhere.
10-37: Well-defined interface for retrieving entitlements and access.Declaring two GET operations in a single interface is clear, and applying separate routes for each method is consistent with REST best practices. The docstrings provide helpful context for both calls.
39-50: Clear definition of theCustomerAccessmodel.Exposing a map of entitlements by feature key provides a straightforward structure for clients. The doc comment is descriptive and aligns with the purpose of the endpoint.
52-64: Extension ofEntitlementValuewithidfield is consistent.
EntitlementValueWithIdfollows a logical pattern by keeping existing fields and adding the entitlement ID. Marking the ID property with a@summaryannotation is a good practice for documentation clarity.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
api/client/javascript/src/client/schemas.ts (1)
604-623:⚠️ Potential issueFix inconsistent path parameter definition
The path definition at
/api/v1/customers/{customerIdOrKey}/accesshaspath?: neveron line 608, which contradicts the operation definition that correctly requires acustomerIdOrKeypath parameter in lines 13199-13201.Apply this change:
- path?: never + path: { + customerIdOrKey: string + }
🧹 Nitpick comments (4)
api/openapi.cloud.yaml (1)
2918-2990: New Customer Access Endpoint DefinitionThe GET operation for the
/api/v1/customers/{customerIdOrKey}/accessendpoint is well-structured and includes comprehensive parameter validation and diverse error responses. The complex regex pattern for thecustomerIdOrKeyparameter appears robust; please double-check that it fully supports all expected customer ID formats without inadvertently rejecting valid inputs.api/openapi.yaml (1)
3300-3304: Review Comment: Update of Tags for the Subscriptions EndpointThe changes add the tags
EntitlementsandCustomersfor the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint. This update improves consistency by grouping related endpoints.
Make sure that these tags accurately represent the functionality of the subscriptions endpoint and align with your overall API tagging strategy.api/spec/src/entitlements/customer.tsp (2)
10-13: Consider adding an interface-level doc comment.
While each operation is documented, consider adding a high-level doc comment explaining the overall purpose of theCustomerinterface for consistency.
27-37: Consider distinguishing authorization failure from missing resource.
It may be beneficial to include a403 Forbiddenor similar response type instead of bundling everything intoOpenMeter.CommonErrorsorNotFoundError. This can help API consumers differentiate between non-existent resources and insufficient privileges.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
api/client/javascript/src/client/schemas.ts(4 hunks)api/openapi.cloud.yaml(3 hunks)api/openapi.yaml(3 hunks)api/spec/src/entitlements/customer.tsp(1 hunks)openmeter/customer/httpdriver/apimapping.go(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/customer/httpdriver/apimapping.go
🧰 Additional context used
🧬 Code Definitions (1)
api/client/javascript/src/client/schemas.ts (2)
api/client/go/client.gen.go (1)
CustomerAccess(1656-1660)api/api.gen.go (1)
CustomerAccess(1791-1795)
⏰ Context from checks skipped due to timeout of 90000ms (7)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Analyze (go)
🔇 Additional comments (8)
api/openapi.cloud.yaml (1)
3301-3307: Consistent Tagging for Subscriptions EndpointThe addition of tags
EntitlementsandCustomersfor the/api/v1/customers/{customerIdOrKey}/subscriptionsendpoint is consistent with the new endpoint’s grouping, ensuring logical categorization across customer-related endpoints. Verify that this covers all desired API routes under these tags.api/client/javascript/src/client/schemas.ts (3)
3139-3146: LGTM: CustomerAccess schema correctly definedThe schema definition for
CustomerAccessproperly describes the entitlements map, which corresponds with definitions in other files.
8956-8956: LGTM: Type export added for convenienceAdding the exported type makes the schema more accessible to client code.
13195-13288: LGTM: Operation definition is comprehensiveThe
getCustomerAccessoperation definition includes all necessary components:
- Correct path parameter definition
- Comprehensive status code handling
- Proper response content types
- Detailed documentation comments
This aligns with the PR objective of adding functionality to retrieve customer access entitlements.
api/openapi.yaml (2)
2917-2988: Review Comment: New/api/v1/customers/{customerIdOrKey}/accessEndpoint DefinitionThis new endpoint is clearly defined with proper operation details:
- The operation ID (
getCustomerAccess), summary, and description are clear.- The path parameter
customerIdOrKeyincludes well-defined constraints (minLength, maxLength, and a regex pattern) that appear appropriate for the expected formats.- The responses (status codes 200, 400, 401, 403, 404, 412, 500, 503, and default) are thoroughly specified with their corresponding content types and schema references.
Please verify that the referenced schema
#/components/schemas/CustomerAccess(defined later in the document) fully reflects the intended customer access model.
11522-11535: Review Comment:CustomerAccessSchema DefinitionThe
CustomerAccessschema is well-structured:
- It correctly enforces that the
entitlementsproperty is required.- The
entitlementsproperty is defined as an object whose values are referenced through the$ref: '#/components/schemas/EntitlementValue'.- The field description clearly explains that the entitlements map feature keys to a combined entitlement value and entitlement ID, and the property is marked as read-only.
However, note that the PR objectives mention a model named
EntitlementValueWithId(extendingEntitlementValue) to include the entitlement ID. Please verify whether the reference should be updated to#/components/schemas/EntitlementValueWithId(if intended) or if theEntitlementValueschema has been updated accordingly.api/spec/src/entitlements/customer.tsp (2)
1-3: Imports look good.
These are the standard TypeSpec libraries for REST, HTTP, and OpenAPI integrations. No concerns here.
5-7:usingstatements are fine.
They correctly reference the required namespaces for HTTP and OpenAPI declarations.
| - my_subject_key | ||
| createdAt: '2024-01-01T01:01:01.001Z' | ||
| updatedAt: '2024-01-01T01:01:01.001Z' | ||
| CustomerAccess: | ||
| type: object | ||
| required: | ||
| - entitlements | ||
| properties: | ||
| entitlements: | ||
| type: object | ||
| additionalProperties: | ||
| $ref: '#/components/schemas/EntitlementValue' | ||
| description: |- | ||
| Map of entitlements the customer has access to. | ||
| The key is the feature key, the value is the entitlement value + the entitlement ID. | ||
| readOnly: true | ||
| description: CustomerAccess describes what features the customer has access to. | ||
| CustomerAppData: |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
CustomerAccess Schema Definition Review
The newly added CustomerAccess schema correctly marks entitlements as a required, read-only property and maps it to an object with additional properties referencing EntitlementValue. However, the PR objectives describe the entitlement values as including an entitlement ID. If the intent was to provide both the value and the ID, consider updating the reference from #/components/schemas/EntitlementValue to #/components/schemas/EntitlementValueWithId or adjust the property description accordingly.
Below is a shell script to verify the review comment’s concerns. It extracts the relevant snippet from api/openapi.cloud.yaml and searches the repository for any mention of a schema named EntitlementValueWithId (which would support the intent of including an entitlement ID) as well as for any explicit mentions of "entitlement ID" in comments or definitions:
Please run these scripts to gather the necessary verification details. Once you have the output:
- If a definition for
EntitlementValueWithIdis found (or references to an entitlement ID exist): Update theCustomerAccessschema so that the reference includes the entitlement ID (i.e. switch to#/components/schemas/EntitlementValueWithId). - If not: Either confirm that the current reference to
EntitlementValueis correct or adjust the comment/documentation to match.
Once validated, you can update the review comment accordingly.
**
🏁 Script executed:
#!/bin/bash
# Step 1: Extract the snippet around the reported lines to verify context
echo "Extracting snippet from api/openapi.cloud.yaml (lines 11640-11670):"
sed -n '11640,11670p' api/openapi.cloud.yaml
# Step 2: Check if a schema for EntitlementValueWithId exists in the repository
echo "Searching for 'components/schemas/EntitlementValueWithId' in the repository:"
rg "components/schemas/EntitlementValueWithId" -n .
# Step 3: Look for any mention of 'entitlement ID' in the repository to see if such detail is noted elsewhere
echo "Searching for 'entitlement ID' references in the repository:"
rg "entitlement ID" -n .Length of output: 3044
Clarify Entitlement Schema Logic in CustomerAccess Definition
- The PR objectives indicate that entitlement entries should include an entitlement ID. However, the
CustomerAccessschema currently references#/components/schemas/EntitlementValue, and no definition forEntitlementValueWithIdexists in the repository. - To resolve this discrepancy, please either:
- Update the
$refto point to a newly created or existing schema (e.g.,EntitlementValueWithId) that supports both the value and the entitlement ID, or - Adjust the property description to reflect the actual structure of
EntitlementValue.
- Update the
| /** | ||
| * CustomerAccess describes what features the customer has access to. | ||
| */ | ||
| @friendlyName("CustomerAccess") | ||
| model CustomerAccess { | ||
| /** | ||
| * Map of entitlements the customer has access to. | ||
| * The key is the feature key, the value is the entitlement value + the entitlement ID. | ||
| */ | ||
| @visibility(Lifecycle.Read) | ||
| entitlements: Record<EntitlementValue>; | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Confirm usage of EntitlementValue instead of EntitlementValueWithId.
The documentation states that the record value includes an entitlement ID, yet the property type is EntitlementValue. Ensure this aligns with your intended data model or switch to EntitlementValueWithId if needed.
If the code is meant to reference EntitlementValueWithId, please run the following script to locate its definition and confirm usage:
🏁 Script executed:
#!/bin/bash
rg -A 5 'EntitlementValueWithId'Length of output: 1539
Action: Update the entitlements field to use EntitlementValueWithId to maintain consistency
Based on the verification, the codebase shows that the type EntitlementValueWithId is used in other parts (see openmeter/entitlement/access.go and connector.go) to represent a value that includes both the entitlement and its ID. Since the documentation in the CustomerAccess model clearly states that the record value comprises an entitlement value plus the entitlement ID, you should update the type accordingly.
- File:
api/spec/src/entitlements/customer.tsp(Lines 39-50) - Change: Replace
with
entitlements: Record<EntitlementValue>;
entitlements: Record<EntitlementValueWithId>;
This change will ensure that the data model accurately reflects the intended structure.
| /** | ||
| * Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. | ||
| */ | ||
| @get | ||
| @operationId("getCustomerEntitlementValue") | ||
| @route("/entitlements/{featureKey}/value") | ||
| @summary("Get entitlement value") | ||
| getCustomerEntitlementValue( | ||
| @path customerIdOrKey: ULIDOrKey, | ||
| @path featureKey: Key, | ||
| @query(#{ explode: true }) time?: DateTime, | ||
| ): EntitlementValue | OpenMeter.CommonErrors | OpenMeter.NotFoundError; |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Validate optional time parameter.
Currently, if time is invalid or cannot be parsed, the specification doesn’t clarify whether a 400 Bad Request or similar should be returned. Verifying proper error responses for invalid query formats can improve API reliability.
To confirm, run the following script to locate and check downstream handling of the time parameter in the codebase:
🏁 Script executed:
#!/bin/bash
# Searching references to the 'time' query parameter
rg -A 3 'time\?: DateTime'Length of output: 757
Action: Define explicit error responses for invalid 'time' parameters
The current specification in api/spec/src/entitlements/customer.tsp (and similarly in api/spec/src/entitlements/subjects.tsp) declares the optional time query parameter as a DateTime but does not specify what happens when the provided value is invalid or unparseable. This lack of clarity might lead to inconsistent behavior across the API endpoints.
- Recommendation: Update the API specification to explicitly document that an invalid
timeparameter should result in a clear error response (e.g., a 400 Bad Request). This will help improve API reliability and ensure consistent error handling. - Additional Note: As seen in
api/spec/src/events.tsp, there is a similar use of thetimeparameter (albeit with a nullable type). Please verify that the error handling across all endpoints using this parameter is consistent.
Overview
Notes for reviewer
Summary by CodeRabbit
New Features
Bug Fixes
Tests