Skip to content

Credit API Refactors (History Rewrite Part I)#2369

Merged
GAlexIHU merged 5 commits intomainfrom
galexi/history-rewrite
Mar 7, 2025
Merged

Credit API Refactors (History Rewrite Part I)#2369
GAlexIHU merged 5 commits intomainfrom
galexi/history-rewrite

Conversation

@GAlexIHU
Copy link
Contributor

@GAlexIHU GAlexIHU commented Mar 3, 2025

Overview

Internal API refactors, precursor to history PR, no changes in functionality.

  • Combine OwnerConnector methods into one for easier use
  • get rid of unnecessary type aliases like old Owner and NamespacedOwner types

Summary by CodeRabbit

  • Refactor

    • Standardized how owner identifiers are handled across credit, grant, and entitlement features to simplify data processing and improve consistency.
  • Tests

    • Updated test scenarios to align with the new owner identification approach, ensuring enhanced reliability and stability throughout the system.

@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Mar 3, 2025
@GAlexIHU GAlexIHU requested a review from a team as a code owner March 3, 2025 13:16
@GAlexIHU GAlexIHU enabled auto-merge (squash) March 3, 2025 13:41
@GAlexIHU GAlexIHU force-pushed the galexi/history-rewrite branch from 9a07d7a to ec3e9fb Compare March 3, 2025 18:07
@GAlexIHU GAlexIHU force-pushed the galexi/history-rewrite branch from ec3e9fb to 37b2c68 Compare March 7, 2025 11:34
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes update the owner type used across multiple modules by replacing the custom type grant.NamespacedOwner with models.NamespacedID. Method signatures, interface declarations, variable definitions, and error messages have been modified accordingly to access the owner’s identifier directly without unnecessary conversions. Minor updates include renaming of methods (for example, replacing GetMeter with DescribeOwner) and adjustments in test cases. The overall functionality and control flow remain unchanged while the representation of ownership is simplified and standardized.

Changes

File(s) Change Summary
openmeter/credit/adapter/balance_snapshot.go Updated method signatures in InvalidateAfter, GetLatestValidAt, and Save to replace grant.NamespacedOwner with models.NamespacedID; adjusted access to owner’s ID.
openmeter/credit/adapter/grant.go Modified CreateGrant, ListGrants, and ListActiveGrantsBetween to use models.NamespacedID without extra string conversions.
openmeter/credit/balance.go and openmeter/credit/balance/repository.go Updated BalanceConnector interface and SnapshotRepo interface methods to use models.NamespacedID; adjusted error messages and field types.
openmeter/credit/grant.go and openmeter/credit/grant/grant.go Removed intermediate NamespacedOwner abstraction; changed Grant.OwnerID type from custom type to string and updated GetNamespacedOwner to return models.NamespacedID.
openmeter/credit/grant/owner_connector.go Introduced a new Owner struct with a GetSubjectKey method; updated various OwnerConnector method signatures to accept models.NamespacedID.
openmeter/credit/grant/repo.go Revised OwnerID fields in ListParams and RepoCreateInput and updated the ListActiveGrantsBetween method signature.
openmeter/credit/helper.go Changed function signatures (e.g., getLastValidBalanceSnapshotForOwnerAt, buildEngineForOwner) to use models.NamespacedID and replaced GetMeter with DescribeOwner internally.
openmeter/server/server_test.go Updated NoopGrantConnector’s CreateGrant signature to accept models.NamespacedID for the owner parameter.
openmeter/entitlement/balanceworker/worker.go Removed redundant string conversions for event.OwnerID in event handling.
Files under openmeter/entitlement/metered/ (including balance.go, balance_test.go, connector.go, entitlement_grant.go, grant_owner_adapter.go, grant_owner_adapter_test.go, reset.go, reset_test.go) Replaced grant.NamespacedOwner with models.NamespacedID for ownership handling and removed unnecessary type conversions in both runtime and test code.
test/entitlement/regression/scenario_test.go Updated grant creation and balance snapshot calls to directly use entitlement.ID instead of converting via grant.Owner.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GrantConnector
    participant OwnerConnector
    participant Repository

    Client->>GrantConnector: CreateGrant(ownerID, input)
    GrantConnector->>OwnerConnector: DescribeOwner(ownerID)
    OwnerConnector-->>GrantConnector: Owner {Namespace, Meter, QueryParams, ResetBehavior}
    GrantConnector->>Repository: CreateGrant(owner, input)
    Repository-->>GrantConnector: Grant & Response
    GrantConnector-->>Client: Return Grant / Error
Loading

Poem

I'm a little rabbit, hopping with delight,
For a world of streamlined IDs shining bright.
No more casting or wrapping in disguise,
Just a simple owner in front of our eyes.
Codes now sing a tidy, clear refrain,
Carrots and changes, a merry refrain!
Hopping through refactors with a joyful bite.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
openmeter/credit/balance.go (1)

63-66: Inconsistency in error message

The error message on line 65 still references owner.ID but should reference ownerID.ID to be consistent with the parameter name change.

-	return nil, fmt.Errorf("failed to describe owner %s: %w", owner.ID, err)
+	return nil, fmt.Errorf("failed to describe owner %s: %w", ownerID.ID, err)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a0cd69 and 37b2c68.

📒 Files selected for processing (21)
  • openmeter/credit/adapter/balance_snapshot.go (3 hunks)
  • openmeter/credit/adapter/grant.go (4 hunks)
  • openmeter/credit/balance.go (12 hunks)
  • openmeter/credit/balance/repository.go (1 hunks)
  • openmeter/credit/grant.go (7 hunks)
  • openmeter/credit/grant/events.go (1 hunks)
  • openmeter/credit/grant/grant.go (2 hunks)
  • openmeter/credit/grant/owner_connector.go (2 hunks)
  • openmeter/credit/grant/repo.go (3 hunks)
  • openmeter/credit/helper.go (7 hunks)
  • openmeter/entitlement/balanceworker/worker.go (2 hunks)
  • openmeter/entitlement/metered/balance.go (9 hunks)
  • openmeter/entitlement/metered/balance_test.go (15 hunks)
  • openmeter/entitlement/metered/connector.go (1 hunks)
  • openmeter/entitlement/metered/entitlement_grant.go (3 hunks)
  • openmeter/entitlement/metered/grant_owner_adapter.go (10 hunks)
  • openmeter/entitlement/metered/grant_owner_adapter_test.go (8 hunks)
  • openmeter/entitlement/metered/reset.go (1 hunks)
  • openmeter/entitlement/metered/reset_test.go (19 hunks)
  • openmeter/server/server_test.go (1 hunks)
  • test/entitlement/regression/scenario_test.go (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (51)
openmeter/credit/grant/events.go (1)

46-46: LGTM: Direct resource path construction.

This change simplifies the code by passing the e.OwnerID directly to the ComposeResourcePath function without type conversion, which aligns with the PR objective of standardizing ownership representation.

openmeter/entitlement/metered/grant_owner_adapter_test.go (1)

62-65: Simplifies type usage by replacing custom owner type with standard model.

The change replaces the custom grant.NamespacedOwner type with the standard models.NamespacedID type, which aligns with the PR objective of eliminating unnecessary type aliases. This simplifies the code and makes it more consistent with the rest of the codebase.

Also applies to: 139-142, 186-189, 254-257, 313-316, 357-360, 413-416, 469-472

openmeter/entitlement/metered/reset.go (1)

20-23: Simplifies owner type representation.

This change replaces the custom grant.NamespacedOwner type with the standard models.NamespacedID type, removing the unnecessary conversion through grant.Owner(). This aligns with the PR objective of eliminating unnecessary type aliases and simplifies the code.

test/entitlement/regression/scenario_test.go (2)

66-69: Standardizes owner type across test scenarios.

The change consistently replaces the custom grant.NamespacedOwner type with the standard models.NamespacedID type across all test scenarios, removing unnecessary type conversions. This aligns with the PR objective of eliminating unnecessary type aliases and makes the tests more consistent with the updated implementation.

Also applies to: 84-87, 129-132, 186-189, 214-218, 254-257, 313-316, 359-362, 413-416, 498-501, 534-537


350-353: Standardizes owner type in balance snapshot operations.

The change replaces the custom grant.NamespacedOwner type with the standard models.NamespacedID type in the balance snapshot repository call, which aligns with the standardization across the rest of the codebase.

openmeter/entitlement/metered/reset_test.go (1)

214-214: Consistent ownership model simplification

The changes in this file are part of a broader effort to simplify the ownership representation by removing unnecessary type abstractions. The code now directly uses string IDs instead of a custom Owner type and employs models.NamespacedID instead of the custom NamespacedOwner type.

Also applies to: 231-234, 236-239, 286-287, 297-298, 325-328, 355-356, 366-367, 397-400, 427-428, 438-439, 469-472, 536-537, 547-548, 575-578, 588-589, 616-619, 650-651, 675-676, 722-723

openmeter/entitlement/metered/balance_test.go (1)

191-192: Consistent ownership model simplification

The changes in this test file follow the same pattern as seen in other files, switching from custom ownership types to direct string IDs and standard models.NamespacedID structures. This refactoring improves code clarity by removing unnecessary abstractions while maintaining the same functionality.

Also applies to: 201-202, 243-246, 249-250, 323-326, 329-330, 477-478, 488-489, 499-500, 536-537, 588-589, 616-619, 650-651, 675-676, 722-723, 746-747, 756-758, 836-837, 846-848

openmeter/credit/grant/repo.go (1)

43-43: Core ownership model refactoring

These changes represent the core refactoring of the ownership model in the repository layer:

  1. Simplified the OwnerID field types from custom Owner type to simple string
  2. Updated method signatures to use standard models.NamespacedID instead of custom NamespacedOwner type

This refactoring reduces abstraction layers in the codebase, making it more straightforward and easier to maintain.

Also applies to: 57-57, 76-76

openmeter/credit/grant/grant.go (1)

20-20: Fundamental data model simplification

These changes complete the ownership model refactoring by:

  1. Changing the core Grant struct to use a simple string for OwnerID rather than a custom type
  2. Updating the GetNamespacedOwner method to return the standard models.NamespacedID type

This simplification of the fundamental data model makes the code more maintainable and removes unnecessary abstraction layers while preserving the same functionality.

Also applies to: 118-123

openmeter/credit/grant.go (2)

18-19: Unified parameter usage for CreateGrant
Refactoring from NamespacedOwner to models.NamespacedID is consistent and straightforward. The switch to DescribeOwner for retrieving the owner and truncating to the meter’s window size is logically sound. No significant concerns—good work!

Also applies to: 35-35, 44-44, 48-48, 53-53, 62-62, 67-68, 84-84, 89-89, 91-91, 94-94, 97-97


120-120: Updated approach for VoidGrant
The new usage of ownerID and calls to DescribeOwner, LockOwnerForTx, and InvalidateAfter aligns with the refactored interface. Concurrency handling via owner-level locks is clearly addressed. No issues found.

Also applies to: 128-133, 145-145, 151-151, 158-158

openmeter/credit/grant/owner_connector.go (2)

16-29: New Owner struct
Embedding models.NamespacedID and including Meter, DefaultQueryParams, and ResetBehavior within the Owner struct neatly consolidates the data. The GetSubjectKey() method is a clean, direct way to retrieve the subject. This greatly improves clarity.


46-46: Refined interface with DescribeOwner
Switching from NamespacedOwner to models.NamespacedID unifies the codebase. The addition of DescribeOwner to the interface provides a more direct and consistent way of fetching the owner’s details. No concerns here.

Also applies to: 52-54, 56-57, 61-61

openmeter/entitlement/metered/grant_owner_adapter.go (3)

46-101: DescribeOwner implementation
Fetching the linked entitlement, meter, and subject key to construct grant.Owner is streamlined. The error handling paths for missing or invalid data (feature, meter, etc.) are handled clearly, preventing null references. Nice work.


103-145: Usage period retrieval methods
Adapting these methods to use models.NamespacedID (e.g., GetStartOfMeasurement, GetUsagePeriodStartAt, GetResetTimelineInclusive) is in line with the refactoring goals. The operations for computing and resetting usage periods remain clear and appear logically correct.

Also applies to: 147-280


306-349: Usage period finalization
The approach to ending usage periods (EndCurrentUsagePeriod), updating the entitlement usage period, and locking the owner for transactional safety looks robust. Keeping everything within a single transaction ensures consistency. No issues noted.

Also applies to: 351-378, 380-387

openmeter/server/server_test.go (1)

648-648: Type change aligns with standardized owner representation

The parameter type for owner has been updated from grant.NamespacedOwner to models.NamespacedID, which is part of the larger standardization effort to consolidate ownership representation across the codebase.

openmeter/entitlement/metered/connector.go (1)

209-212: Simplified owner ID representation

The change replaces grant.NamespacedOwner with models.NamespacedID and directly assigns metered.ID to the ID field without unnecessary conversion, making the code more concise and consistent with the rest of the codebase.

openmeter/entitlement/balanceworker/worker.go (2)

171-173: Streamlined owner ID handling

The change eliminates unnecessary string conversion for event.OwnerID, using the ID directly when constructing the NamespacedID and resource path. This simplifies the code while maintaining the same functionality.


182-184: Streamlined owner ID handling

Similar to the earlier change, this eliminates unnecessary string conversion for event.OwnerID, using the ID directly when constructing the NamespacedID and resource path for the void event handler.

openmeter/entitlement/metered/entitlement_grant.go (3)

33-36: Simplified owner ID representation

The change replaces grant.NamespacedOwner with models.NamespacedID and assigns ent.ID directly to the ID field, making the code more straightforward and consistent with the standardized approach to ownership representation.


74-75: Direct owner ID assignment

Updated to use ent.ID directly rather than converting through grant.Owner(ent.ID), which simplifies the code and aligns with the ownership type standardization.


119-120: Simplified entitlement ID assignment

Directly assigns grant.OwnerID to EntitlementID without unnecessary type conversion, making the code more concise and easier to understand.

openmeter/credit/adapter/grant.go (4)

37-37: Clean type handling in SetOwnerID

The code now directly uses grant.OwnerID without string conversion, which aligns with the refactoring to standardize ownership representation.


76-76: Simplified owner ID filtering

Direct use of the OwnerID parameter in the where clause improves code clarity by removing unnecessary type conversions.


168-170: Method signature improved with models.NamespacedID

Replacing grant.NamespacedOwner with models.NamespacedID standardizes the owner representation across the codebase, making it more consistent and easier to maintain.


219-219: Simplified owner ID assignment

Direct assignment of entity.OwnerID removes unnecessary conversion through grant.Owner function, streamlining the code.

openmeter/credit/balance/repository.go (3)

9-9: Clean import addition

Added models package import to support the type changes in the interface.


13-16: Interface methods standardized with models.NamespacedID

All SnapshotRepo interface methods now consistently use models.NamespacedID instead of the custom grant.NamespacedOwner type, which enhances API clarity and simplifies the contract.


23-23: Error type updated for consistency

The Owner field in NoSavedBalanceForOwnerError now uses models.NamespacedID, maintaining type consistency across the error handling system.

openmeter/entitlement/metered/balance.go (8)

59-62: Simplified owner initialization

Constructor for models.NamespacedID is now more direct, eliminating unnecessary type conversions and enhancing code readability.


71-73: Improved method naming and error handling

Changed from GetMeter to more descriptive DescribeOwner method and updated the error message to accurately reflect the operation being performed.


83-83: Direct access to owner query parameters

Now directly accessing owner.DefaultQueryParams instead of using intermediate conversions, improving code clarity.


92-92: Simplified meter access

Using owner.Meter directly to query the meter, which streamlines the code by removing unnecessary conversions.


143-149: Consistent owner description approach

Using DescribeOwner with models.NamespacedID maintains consistency with earlier changes in the file and improves error message clarity.


174-175: Updated query method parameters

Correctly passing owner namespace and meter when querying, maintaining functionality while using the new type structure.


252-253: Clean balance history retrieval

Now using owner.NamespacedID directly when getting balance history, aligning with the standardized approach to owner identification.


314-314: Consistent query parameter usage

Using owner.NamespacedID.Namespace for meter queries maintains consistency with other parameter usage in the method.

openmeter/credit/adapter/balance_snapshot.go (4)

13-13: Clean import addition

Added models package import to support the type changes in method signatures.


27-31: Updated InvalidateAfter method signature

Method now uses models.NamespacedID and correctly references owner.ID in the database query, maintaining functionality while using the standardized type.


34-38: Improved GetLatestValidAt implementation

Method signature now uses models.NamespacedID and the database query properly references owner.ID directly, simplifying the code.


55-61: Refactored Save method with consistent type usage

The Save method now uses models.NamespacedID and correctly sets owner ID in the database, maintaining consistency with other methods.

openmeter/credit/balance.go (4)

26-28: Interface signature changes look good

The interface declaration has been updated to use models.NamespacedID instead of the previous type. This aligns with the PR objective of eliminating unnecessary type aliases.


38-39: Parameter name changed to reflect new type

The parameter has been appropriately renamed from owner to ownerID to better reflect its nature as an identifier rather than a complete owner object.


128-131: Error message correctly updated

The error message on line 130 has been correctly updated to reference ownerID.ID.


182-185: Method calls consistently updated

All method calls to the owner connector have been updated to use the new parameter type, and the variable names have been appropriately adjusted.

openmeter/credit/helper.go (5)

24-24: Function signature updated correctly

The function signature has been updated to use models.NamespacedID instead of the previous type, maintaining consistency with the other changes in this PR.


56-66: Clean pattern for getting owner details

The code now uses a clean pattern of first retrieving the owner object with DescribeOwner and then using its properties. This is more maintainable than accessing properties through different method calls.


123-125: Owner-specific properties accessed correctly

The code now consistently accesses owner-specific properties through the owner object returned by DescribeOwner.


156-160: Consistent use of namespace from owner ID

The meter query now correctly uses the namespace from the owner ID, maintaining the functionality while simplifying the type structure.


203-203: Struct definition updated to match new type

The snapshotParams struct has been updated to use the new type for its owner field, ensuring consistency throughout the codebase.

@GAlexIHU GAlexIHU merged commit 77a7595 into main Mar 7, 2025
25 checks passed
@GAlexIHU GAlexIHU deleted the galexi/history-rewrite branch March 7, 2025 12:36
@coderabbitai coderabbitai bot mentioned this pull request Oct 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants