Skip to content

Customer Access API - #2546

Merged
GAlexIHU merged 6 commits into
mainfrom
galexi/customer-access-api
Apr 4, 2025
Merged

GAlexIHU merged 6 commits into
mainfrom
galexi/customer-access-api

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Mar 28, 2025 •

Copy link
Copy Markdown
Contributor

Overview

  • Define access type as
/**
 * 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<EntitlementValueWithId>;
}

/**
 * EntitlementValueWithID extends EntitlementValue with an entitlement ID.
 */
@friendlyName("EntitlementValueWithId")
model EntitlementValueWithId {
  ...EntitlementValue;

  /**
   * The entitlement ID.
   */
  @summary("The entitlement ID")
  id: global.ULID;
}
  • Implement internal methods for resolving it in parallel

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Introduced a new API endpoint for retrieving customer access details, providing a comprehensive view of available feature entitlements.
    • Enhanced customer management functionalities with improved access handling, including robust error reporting and refined response formats.
  • Bug Fixes

    • Removed outdated method for checking customer entitlement values, streamlining the API.
  • Tests

    • Expanded automated test coverage to verify customer creation and access checks, ensuring reliable and accurate API responses.

@GAlexIHU GAlexIHU added the release-note/feature Release note: Exciting New Features label Mar 28, 2025
@GAlexIHU GAlexIHU self-assigned this Mar 28, 2025
@GAlexIHU
GAlexIHU requested a review from a team as a code owner March 28, 2025 13:18
@coderabbitai

coderabbitai Bot commented Mar 28, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request extends the API with a new endpoint at /api/v1/customers/{customerIdOrKey}/access. It adds a new operation (getCustomerAccess), several new schemas (CustomerAccess, EntitlementValueWithId), and associated TypeSpec definitions. Additionally, the PR updates API specifications, HTTP handler layers, service methods, and tests to incorporate customer access retrieval, while removing or modifying obsolete entitlement-check methods.

Changes

File(s) Change Summary
api/.../client/schemas.ts, api/openapi.cloud.yaml, api/openapi.yaml Added new endpoint /api/v1/customers/{customerIdOrKey}/access with operation getCustomerAccess and new schemas CustomerAccess and EntitlementValueWithId.
api/spec/src/.../main.tsp, api/spec/src/customer.tsp, api/spec/src/entitlements/customer.tsp, api/spec/src/entitlements/main.tsp Updated TypeSpec definitions: introduced a new Customer interface with methods (getCustomerAccess, getCustomerEntitlementValue), added models, removed the old getCustomerEntitlementValue in one spec, and included customer module imports.
e2e/productcatalog_test.go, openmeter/entitlement/access_test.go, openmeter/entitlement/utils_test.go Enhanced test coverage with a new test case for customer access, added assertions for customer creation responses, and updated dependency setups for entitlement tests.
openmeter/customer/httpdriver/apimapping.go, openmeter/customer/httpdriver/customer.go, openmeter/customer/httpdriver/handler.go Introduced a mapping function to convert entitlement access data to API responses; added new handler types and methods for retrieving customer access.
openmeter/customer/service.go, openmeter/customer/service/customer.go Added a new GetCustomerAccess method in the service layer and updated subject key retrieval logic in entitlement methods.
openmeter/entitlement/access.go, openmeter/entitlement/connector.go Created new types (Access, EntitlementValueWithId) and implemented a concurrent GetAccess method within the entitlement connector.
openmeter/server/router/customer.go, openmeter/server/router/entitlement.go, openmeter/server/server_test.go Removed an obsolete customer entitlement route; added new routes for handling customer access and entitlement value queries, along with corresponding zero-value method implementations in test connectors.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@GAlexIHU
GAlexIHU force-pushed the galexi/customer-access-api branch from 1408bf5 to 4c071dd Compare March 28, 2025 13:19
return c.entitlementRepo.ListEntitlements(ctx, params)
}

func (c *entitlementConnector) GetAccess(ctx context.Context, namespace string, subjectKey string) (Access, error) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the interesting part

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (12)
api/openapi.yaml (1)

12945-12985: EntitlementValueWithId Schema Addition

The introduction of the EntitlementValueWithId schema is comprehensive. It correctly mandates the presence of hasAccess and id, 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 Definition

The addition of the /api/v1/customers/{customerIdOrKey}/access endpoint is well-structured. The GET method is clearly defined with:

  • A specific operationId (getCustomerAccess)
  • A concise summary and description
  • Proper parameter validation (using minLength, maxLength, and a regex pattern) for customerIdOrKey
  • Detailed response definitions with appropriate HTTP status codes and response schemas (particularly the reference to CustomerAccess in 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 Schema

The EntitlementValueWithId schema is comprehensively defined with:

  • Mandatory fields (hasAccess and id)
  • Additional fields such as balance, usage, overage, and config with clear descriptions and examples
  • A regex pattern ensuring the proper format for the id

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

  1. The concurrency limit approach (lines 247-249) provides control, but consider making maxConcurrency configurable to accommodate varied system loads.
  2. Your sync.Map usage and type checks (lines 291-303) are handled properly, helping avoid data races. Periodically evaluate potential overhead if entitlements grows 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 in EntitlementValue.
Make sure that EntitlementValue does indeed define a property such as hasAccess, so this documentation remains accurate and clear.


44-49: Specify record key type for clarity (optional).
Currently, you’re using Record<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

📥 Commits

Reviewing files that changed from the base of the PR and between 14f1c88 and 4c071dd.

📒 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 dependencies

The addition of the streamingConnector field 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 Sum

The change from MeterAggregationMax to MeterAggregationSum may 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 mock

The 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 registry

The 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 struct

The 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.tsp

The 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 interface

The new GetCustomerAccess method 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 Implementation

The new endpoint /api/v1/customers/{customerIdOrKey}/access is well-defined. The definition clearly specifies the GET operation with the proper operationId (getCustomerAccess), summary, and description. The parameter customerIdOrKey includes 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 Endpoint

The updated fragment for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint now includes the Entitlements tag along with Customers. This enhanced tagging should help with logical grouping and filtering in API documentation. Please ensure that the inclusion of Entitlements for subscriptions is intentional and aligns with your overall API categorization strategy.


11591-11605: CustomerAccess Schema Definition

The newly added CustomerAccess schema is structured appropriately. It defines an object with a required entitlements property that is designed as a map (using additionalProperties) referencing EntitlementValueWithId. 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 5

Length of output: 3766


Verification Complete: EntitlementValue is Locally Defined

The script output confirms that EntitlementValue is defined in the codebase (specifically in openmeter/entitlement/entitlement_types.go as an interface) and is accessible within openmeter/entitlement/access.go because both files reside in the same package. No additional import is necessary.

api/openapi.cloud.yaml (2)

3301-3307: Consistent Tagging for Subscription Endpoint

In this hunk, the tags for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint 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 Schema

The new CustomerAccess schema is clearly defined as an object with a required entitlements property. The entitlements property is set up as a map (via additionalProperties) linking feature keys to EntitlementValueWithId definitions. The inclusion of the readOnly attribute and a descriptive comment further clarifies the schema's intent.

api/spec/src/cloud/main.tsp (1)

177-181: Addition of Customer interface looks good

This new interface properly extends the base OpenMeter.Entitlements.Customer and 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 assertion

Adding 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 endpoint

The test case properly validates the new customer access functionality by:

  1. Making a request to get customer access
  2. Verifying the response status code is correct
  3. Confirming the response contains entitlements data
  4. Checking that the expected feature key exists
  5. 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 capabilities

The addition of these two methods to the CustomerService interface is appropriate:

  1. GetEntitlementValue provides a way to retrieve individual entitlement values
  2. GetCustomerAccess enables retrieving the complete access information for a customer

Both 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 correctly

These imports are necessary for working with the entitlement types and mapping functions used in the new code.


94-116: Thorough implementation of access mapping function

The MapAccessToAPI function correctly transforms an internal entitlement.Access object to the API api.CustomerAccess representation. It:

  1. Creates a map to hold the transformed entitlements
  2. Iterates through each entitlement in the source object
  3. Properly maps each entitlement value using the existing helper
  4. Handles potential errors during mapping
  5. Constructs API-compatible EntitlementValueWithId objects with all required fields
  6. Returns a properly structured CustomerAccess object

The 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 GetAccess method is correctly implemented in the NoopEntitlementConnector struct, returning an empty entitlement.Access struct and nil error. This is consistent with the "no-op" pattern used throughout the file for testing purposes.


1021-1023: Implementation looks good.

The GetCustomerAccess method is correctly implemented in the NoopCustomerService struct, returning an empty entitlement.Access struct 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 GetSubjectKey method directly and provides a clearer error message when it fails.


79-91: Implementation of GetCustomerAccess looks good.

The method correctly:

  1. Retrieves the customer using the provided input
  2. Gets the subject key from the customer's usage attribution
  3. Handles errors appropriately with clear error messages
  4. 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 Access struct is returned. This establishes a baseline behavior for the GetAccess method.


29-73: Test case for single entitlement is comprehensive.

This test thoroughly validates the behavior for a single entitlement:

  1. Sets up the necessary test fixtures with controlled time
  2. Creates a feature and a boolean entitlement
  3. Advances time to ensure consistent behavior
  4. Verifies that the returned access contains the correct entitlement
  5. 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:

  1. Creates multiple features and entitlements in a loop
  2. Tracks the entitlement IDs for verification
  3. Verifies that all entitlements are present in the returned access
  4. 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:

  1. Creates boolean, static, and metered entitlements
  2. Sets up a mock event for the metered entitlement
  3. Verifies that all three entitlement types are correctly included in the returned access
  4. 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:

  1. Creates a larger set of features and entitlements
  2. Ensures all entitlements are correctly returned in the access result
  3. 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, and semaphore) is generally sound. However, please verify that your approach to semaphore acquisition (line 258) aligns properly with the golang.org/x/sync/semaphore usage patterns. Some implementations require additional arguments for Acquire.


86-90: Interface expansion.

Adding the GetAccess method to the Connector interface 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, and GetCustomerAccessParams follows an established pattern. This maintains clarity and consistency with existing handler definitions.


367-402: Ensure robust test coverage.

The GetCustomerAccess handler 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 CustomerAccess schema is clearly documented and accurately typed. No issues found.


8799-8799: Export statement is fine.

No issues with the new CustomerAccess type export; it's consistent with the schema definition.


8851-8852: No concerns here.

The EntitlementValueWithId export is correct and aligns well with the newly introduced schema.


13024-13117: Verify error response coverage.

The new getCustomerAccess operation 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 for getCustomerAccess.
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!
Extending EntitlementValue with an id field in EntitlementValueWithId is clear and concise.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (11)
api/openapi.yaml (2)

2917-2988: New Customer Access Endpoint Specification
The new /api/v1/customers/{customerIdOrKey}/access endpoint 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 an id (along with hasAccess and optional metering properties) fulfills the new model requirements. A minor improvement: there is a typographical error in the description for hasAccess ("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 & Consistency

The EntitlementValueWithId schema correctly extends the base entitlement model with required fields including hasAccess and id, along with additional optional properties for metered entitlements. A few minor nitpicks:

  • In the hasAccess property description, "accross" should be corrected to "across."
  • In the balance property 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 configurable

The 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 to setupDependencies for 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 for getCustomerAccess.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14f1c88 and 4c071dd.

📒 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 available

Adding the import for ./customer.tsp integrates the customer-related functionality into the entitlements namespace. Based on the PR objectives, this properly connects the new CustomerAccess model with the existing entitlements system.

openmeter/customer/httpdriver/handler.go (1)

25-25: Addition of GetCustomerAccess is consistent with PR objectives

The new GetCustomerAccess() GetCustomerAccessHandler method 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 from customer.go.

api/openapi.yaml (2)

3300-3306: Subscriptions Endpoint Tag Update
The addition of the Entitlements tag alongside Customers for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint 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 added CustomerAccess schema is well defined. It requires the entitlements property, which correctly uses an additionalProperties schema reference to EntitlementValueWithId. 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 CustomerAccess model for defining entitlement access types.

api/openapi.cloud.yaml (3)

2918-2990: New "getCustomerAccess" Endpoint Specification

The new endpoint for retrieving customer access is clearly defined with a descriptive operationId, summary, and detailed response sections. The path parameter customerIdOrKey includes 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 Specification

This hunk introduces the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint with the appropriate tags. However, the definition appears incomplete (only the beginning of the get method is visible). Please verify that the full specification—such as an operationId, summary, parameters, and response details—is provided in another part of the spec or will be added soon.


11716-11729: Addition of the CustomerAccess Schema

The new CustomerAccess schema is well-defined, requiring an entitlements property that maps feature keys to EntitlementValueWithId objects. 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 type

The 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 EntitlementValueWithId

This 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 good

The CustomerService interface has been enhanced with:

  1. The GetEntitlementValue method (retained)
  2. 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 added

The imports for entitlement and entitlementdriver packages are necessary for the new functionality.


94-116: Well-implemented mapping function

The MapAccessToAPI function correctly transforms entitlement.Access to api.CustomerAccess:

  1. Creates a map for API entitlements
  2. Properly handles each entitlement value by delegating to entitlementdriver.MapEntitlementValueToAPI
  3. Includes appropriate error handling
  4. 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 NoopEntitlementConnector

This 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 NoopCustomerService

The 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 context

The 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 GetCustomerAccess

The 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 dependencies

Adding this field to the test dependencies struct ensures proper test setup and teardown for streaming functionality.


117-118: Consistent streamingConnector instantiation and usage

The 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 MeterAggregationMax to MeterAggregationSum may 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 2

Length of output: 4766


Verified Aggregation Type Change: Confirmation & Alignment Required

The update from MeterAggregationMax to MeterAggregationSum has been verified. Our grep search confirms that MeterAggregationSum is consistently used across the production code (e.g., in files like test/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.go have 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 customerdriver

Appropriate import for the new customer-related handler methods.


111-113: Clear section comment for Customer APIs

Good practice to add a section comment to distinguish the customer-specific API endpoints.


116-121: Proper implementation of GetCustomerEntitlementValue handler

The handler follows the established pattern for routing in the codebase, maintaining consistency with other handler methods.


125-129: Well-defined GetCustomerAccess handler

The 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 primitives

Appropriate imports for implementing parallel processing in the new GetAccess method.

Also applies to: 11-12


87-89: Clear interface definition for GetAccess method

The method signature and comment clearly describe the purpose and return value of the new method.


231-241: Proper initialization and empty case handling

The method correctly handles the case where no entitlements are found, returning an empty Access object rather than an error.


243-265: Well-implemented concurrency control

The code uses appropriate concurrency primitives:

  • sync.Map for thread-safe result collection
  • errgroup for coordinated error handling
  • semaphore to limit concurrency to 10 parallel operations

This approach will prevent overwhelming the system while still providing performance benefits.


267-277: Efficient entitlement value retrieval and storage

The 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 results

The code carefully converts from sync.Map to 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 for CustomerAccess and EntitlementValueWithId are 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 CustomerAccess schema and the entitlements property appear to be well-defined for storing multiple EntitlementValueWithId objects. 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 EntitlementValueWithId is straightforward and aligned with the new schema definitions.


13024-13117: Confirm complete test coverage and consider clarifying non-happy-path scenarios.

The getCustomerAccess operation 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.

@GAlexIHU
GAlexIHU force-pushed the galexi/customer-access-api branch from 4c071dd to 547890f Compare March 31, 2025 09:54

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (11)
api/openapi.yaml (4)

2917-2989: New Customer Access Endpoint Definition is Well Structured
The new endpoint /api/v1/customers/{customerIdOrKey}/access is 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 the example property) 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}/subscriptions endpoint 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 new CustomerAccess schema is implemented correctly as an object requiring the entitlements property. The use of additionalProperties referring to EntitlementValueWithId is consistent with the intent of mapping feature keys to their entitlement details. The readOnly: true attribute reinforces that this data is output only.
**
** You might consider adding an example for the CustomerAccess object to show expected key–value pairs.


12912-12952: EntitlementValueWithId Schema Defined with Minor Inconsistency in Naming
This new schema extends entitlement details by including an id field along with other optional properties such as balance, usage, overage, and config. The required fields (hasAccess and id) 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 is EntitlementValueWithId. 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 Improvements

The new EntitlementValueWithId schema 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 balance property'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 configurable

The 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 description

There'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 documentation

The id field has both a standalone description line and a @description tag 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.
• MapAccessToAPI usage is consistent with similar mapping functions in this file.
• Consider adding an explicit check for nil return 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c071dd and 547890f.

📒 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 functionality

The addition of imports for the entitlement package and entitlementdriver is necessary to support the new mapping function.


94-116: Well-structured implementation of MapAccessToAPI

The function correctly maps an entitlement.Access object to an api.CustomerAccess object, 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 of GetAccess for test mock

The GetAccess method is appropriately implemented for the NoopEntitlementConnector mock, returning empty values consistent with the "noop" pattern used throughout the test file.


1021-1023: Correct implementation of GetCustomerAccess for test mock

The GetCustomerAccess method is correctly implemented for the NoopCustomerService mock, 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 handling

The 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 method

The new GetCustomerAccess method follows a consistent pattern with other service methods. It properly handles errors at each step and returns a structured entitlement.Access object as required by the PR objectives. The method effectively reuses existing code paths (GetCustomer and subject key retrieval) before fetching access information through the entitlement connector.

api/openapi.cloud.yaml (3)

2918-2990: New Endpoint Definition: Validate Customer Access Specification

The new /api/v1/customers/{customerIdOrKey}/access endpoint 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 Endpoint

The modifications extending the unexpected problem schema and the inclusion of the "Entitlements" and "Customers" tags for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint 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 Usage

The CustomerAccess schema is introduced as an object with a required property entitlements. Using additionalProperties to reference EntitlementValueWithId effectively 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 endpoints

The 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 method

The documentation clearly explains the purpose of the GetAccess method 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 returns

The 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 handling

The concurrent processing of entitlements is well-implemented using Go's concurrency primitives (errgroup, semaphore). The code:

  1. Properly limits concurrent operations (preventing resource exhaustion)
  2. Creates local copies of variables for goroutines (avoiding closure issues)
  3. Handles errors appropriately at each step

287-315: Thorough error handling during map conversion

The implementation properly handles potential type assertion errors when converting from sync.Map to 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 good

This addition defines a new GET endpoint at /api/v1/customers/{customerIdOrKey}/access to retrieve customer access information, which aligns with the PR objective of introducing customer access APIs.


3188-3195: New CustomerAccess schema implementation looks good

The 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 good

This 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 good

The type exports for CustomerAccess and EntitlementValueWithId are properly defined, making them available for use in the client code.

Also applies to: 8851-8852


13024-13117: Operation definition for getCustomerAccess is comprehensive

The 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.NoError and require.Equal ensures 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, and GetCustomerAccessParams aligns 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.

• CustomerAccess model provides a clear record of featureKey → EntitlementValueWithId.
• EntitlementValueWithId extends the base value with an id field, allowing precise tracking.
• Summaries and friendlyName decorators improve API documentation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
api/spec/src/entitlements/customer.tsp (3)

17-25: Consider clarifying the usage of the optional time parameter.

It's not fully clear whether it represents a historical or future time for entitlement values. Including a short description of how time influences the entitlement lookup would help mitigat confusion.


30-36: Consider supporting a future or past access lookup.

The new getCustomerAccess operation returns the current access. If you need time-based entitlements, consider adding an optional time parameter, similar to getCustomerEntitlementValue, 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 typed Record<Key, EntitlementValueWithId>.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 547890f and e3c574c.

📒 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 EntitlementValue with an id property is concise and clear. Ensure that global.ULID is consistent with your domain requirements for unique identifiers.

@GAlexIHU
GAlexIHU force-pushed the galexi/customer-access-api branch from e3c574c to 809111e Compare April 4, 2025 14:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (8)
api/openapi.cloud.yaml (4)

2918-2990: New Endpoint for Customer Access Retrieval
The new /api/v1/customers/{customerIdOrKey}/access endpoint is clearly defined with a well-structured GET operation. The path parameter customerIdOrKey is constrained appropriately with minLength, 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 the Entitlements tag alongside Customers for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint 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 introduced CustomerAccess schema is well-defined. It mandates the entitlements property, which correctly maps feature keys to entitlement values (using the EntitlementValueWithId schema). 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
The EntitlementValueWithId schema is comprehensive and clearly outlines the properties, including required fields hasAccess and id, as well as optional ones like balance, usage, overage, and config.

  • 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 extends EntitlementValue by adding the entitlement ID and adhering to the documented format.
openmeter/entitlement/connector.go (2)

248-249: Consider making maxConcurrency configurable

The 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 clarity

The 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 error
api/openapi.yaml (2)

2917-2989: Clarify Endpoint Functionality and Parameter Usage

The new endpoint /api/v1/customers/{customerIdOrKey}/access is 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 Consistency

The EntitlementValueWithId schema is comprehensively defined with detailed properties such as hasAccess, balance, usage, overage, config, and id. The use of readOnly: true for 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

📥 Commits

Reviewing files that changed from the base of the PR and between e3c574c and 809111e.

📒 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 of entitlement and entitlementdriver.


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. If access.Entitlements might 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 the GetAccess interface by returning a default entitlement.Access with 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 when UsageAttribution is missing a valid subject key. Otherwise, looks good.

openmeter/server/router/entitlement.go (1)

111-130: LGTM: Well-structured API handlers for customer access

The 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 good

The new method is well-documented with clear comments explaining its purpose and return values.


231-242: Good error handling and early return pattern

The 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 pattern

The concurrent implementation using errgroup and semaphore is excellent for performance while maintaining controlled resource usage. The code correctly:

  1. Uses sync.Map for thread-safe storage
  2. Creates local copies of variables for goroutines
  3. Limits concurrency with a semaphore
  4. Properly handles context cancellation
  5. Waits for all goroutines to complete

This will provide efficient parallel retrieval of entitlement values.


287-315: Good type safety in map conversion

The 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 partialSuccess flags in requests where feasible[1]. For example:

POST /bulk-update?partialSuccess=true

Implement 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-68f728c1ba70 Prevents 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
end

Maintain 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:

  1. Return 202 Accepted with status endpoint
  2. Implement webhooks for completion notifications
  3. 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:


Action Required: Revisit Partial Failure Handling Strategy in GetAccess

The 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 good

This code introduces a new API endpoint for retrieving customer access information, which aligns with the PR objectives.


608-608: Path parameter definition inconsistency

The endpoint path definition has path?: never which contradicts the operation definition that requires a customerIdOrKey path parameter in lines 13238-13240.

-      path?: never
+      path: {
+        customerIdOrKey: string
+      }

3139-3146: CustomerAccess schema definition is well-structured

The 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 information

This 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 defined

The type export properly references the corresponding schema definition.


9046-9047: Type export for EntitlementValueWithId is correctly defined

The type export properly references the corresponding schema definition.


13234-13327: getCustomerAccess operation is well-defined with comprehensive response types

The 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 Endpoints

The 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 Definition

The CustomerAccess schema is introduced clearly with a required property entitlements, which is defined as an object mapping feature keys to EntitlementValueWithId objects. 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.GetCustomerAccess to 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 GetCustomerAccess errors 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 GetCustomerAccess handler in openmeter/customer/httpdriver/customer.go forwards 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 from s.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.GetCustomerAccess returns 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 201 helps 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.Entitlements namespace 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 the CustomerAccess model.

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 of EntitlementValue with id field is consistent.

EntitlementValueWithId follows a logical pattern by keeping existing fields and adding the entitlement ID. Marking the ID property with a @summary annotation is a good practice for documentation clarity.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (1)
api/client/javascript/src/client/schemas.ts (1)

604-623: ⚠️ Potential issue

Fix inconsistent path parameter definition

The path definition at /api/v1/customers/{customerIdOrKey}/access has path?: never on line 608, which contradicts the operation definition that correctly requires a customerIdOrKey path 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 Definition

The GET operation for the /api/v1/customers/{customerIdOrKey}/access endpoint is well-structured and includes comprehensive parameter validation and diverse error responses. The complex regex pattern for the customerIdOrKey parameter 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 Endpoint

The changes add the tags Entitlements and Customers for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint. 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 the Customer interface for consistency.


27-37: Consider distinguishing authorization failure from missing resource.
It may be beneficial to include a 403 Forbidden or similar response type instead of bundling everything into OpenMeter.CommonErrors or NotFoundError. This can help API consumers differentiate between non-existent resources and insufficient privileges.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 809111e and b764264.

📒 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 Endpoint

The addition of tags Entitlements and Customers for the /api/v1/customers/{customerIdOrKey}/subscriptions endpoint 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 defined

The schema definition for CustomerAccess properly describes the entitlements map, which corresponds with definitions in other files.


8956-8956: LGTM: Type export added for convenience

Adding the exported type makes the schema more accessible to client code.


13195-13288: LGTM: Operation definition is comprehensive

The getCustomerAccess operation 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}/access Endpoint Definition

This new endpoint is clearly defined with proper operation details:

  • The operation ID (getCustomerAccess), summary, and description are clear.
  • The path parameter customerIdOrKey includes 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: CustomerAccess Schema Definition

The CustomerAccess schema is well-structured:

  • It correctly enforces that the entitlements property is required.
  • The entitlements property 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 (extending EntitlementValue) to include the entitlement ID. Please verify whether the reference should be updated to #/components/schemas/EntitlementValueWithId (if intended) or if the EntitlementValue schema 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: using statements are fine.
They correctly reference the required namespaces for HTTP and OpenAPI declarations.

Comment thread api/openapi.cloud.yaml
Comment on lines 11644 to 11661
- 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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 EntitlementValueWithId is found (or references to an entitlement ID exist): Update the CustomerAccess schema so that the reference includes the entitlement ID (i.e. switch to #/components/schemas/EntitlementValueWithId).
  • If not: Either confirm that the current reference to EntitlementValue is 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 CustomerAccess schema currently references #/components/schemas/EntitlementValue, and no definition for EntitlementValueWithId exists in the repository.
  • To resolve this discrepancy, please either:
    • Update the $ref to 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.

Comment on lines +39 to +50
/**
* 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>;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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
    entitlements: Record<EntitlementValue>;
    with
    entitlements: Record<EntitlementValueWithId>;

This change will ensure that the data model accurately reflects the intended structure.

Comment on lines +14 to +25
/**
* 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 time parameter 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 the time parameter (albeit with a nullable type). Please verify that the error handling across all endpoints using this parameter is consistent.

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

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants