Repository navigation
Balance & Usage Consistency (History Rewrite Part II) - #2383
Conversation
📝 WalkthroughWalkthroughThis update spans several modules. In the credit package, a new condition was added to include grants effective at the query’s end time, and the balance retrieval interface was revised by replacing old methods with new ones that return a detailed engine result. The grant burn down history now uses a singular history instance with a new snapshot method, and tests were updated to access history via a Segments() method. In the entitlement package, balance methods are restructured to utilize the updated credit interface, and new logic in usage period calculation and tests for late events, resets, and voiding has been introduced. Changes
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
ec3e9fb to
37b2c68
Compare
fd3c4a0 to
9284c3a
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
openmeter/credit/engine/engine.go (1)
31-31: Improved encapsulation of history dataThe change from
[]GrantBurnDownHistorySegmenttoGrantBurnDownHistoryrepresents a better design approach by encapsulating the segments within a dedicated type. This improves the API by providing controlled access to the segments via methods rather than exposing the array directly.openmeter/credit/balance.go (1)
118-127: Consider adding error validation for empty period.The method properly handles time rounding for period.To, but there's no validation that the period is non-empty (From <= To).
func (m *connector) GetBalanceForPeriod(ctx context.Context, ownerID models.NamespacedID, period timeutil.Period) (engine.RunResult, error) { m.logger.Debug("calculating history for owner", "owner", ownerID.ID, "period", period) var def engine.RunResult + // Validate period is not empty + if period.From.After(period.To) { + return def, fmt.Errorf("invalid period: From (%s) is after To (%s)", period.From, period.To) + } + // To include the current last minute lets round it trunc to the next minute if trunc := period.To.Truncate(time.Minute); trunc.Before(period.To) { period.To = trunc.Add(time.Minute)openmeter/entitlement/metered/balance.go (1)
234-240: Consider adding specific error handling for owner not found.Similar to the GetEntitlementBalance method, you might want to handle OwnerNotFoundError specifically here as well.
historyRes, err := e.balanceConnector.GetBalanceForPeriod(ctx, owner.NamespacedID, timeutil.Period{ From: periodToQueryEngine.From, To: periodToQueryEngine.To, }) if err != nil { + if _, ok := err.(*grant.OwnerNotFoundError); ok { + return nil, engine.GrantBurnDownHistory{}, &entitlement.NotFoundError{EntitlementID: entitlementID} + } return nil, engine.GrantBurnDownHistory{}, fmt.Errorf("failed to get balance history: %w", err) }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
openmeter/credit/adapter/grant.go(1 hunks)openmeter/credit/balance.go(5 hunks)openmeter/credit/engine/engine.go(1 hunks)openmeter/credit/engine/history.go(2 hunks)openmeter/credit/engine/reset_test.go(4 hunks)openmeter/credit/engine/run.go(4 hunks)openmeter/credit/engine/run_test.go(6 hunks)openmeter/credit/helper.go(1 hunks)openmeter/entitlement/metered/balance.go(4 hunks)openmeter/entitlement/metered/grant_owner_adapter.go(2 hunks)openmeter/entitlement/metered/lateevents_test.go(1 hunks)openmeter/entitlement/metered/reset_test.go(10 hunks)openmeter/entitlement/metered/utils_test.go(2 hunks)test/entitlement/regression/scenario_test.go(1 hunks)
🔇 Additional comments (37)
openmeter/credit/adapter/grant.go (1)
177-177: Correctly includes grants effective at period endAdding the condition to include grants that are effective exactly at the query end time (
to) ensures proper inclusion of all relevant grants in the calculation.openmeter/credit/helper.go (1)
217-217: Simplified access to history segmentsThis change correctly leverages the new
GrantBurnDownHistorytype by directly accessing its segments through theSegments()method, eliminating the need for additional object creation and error handling that was likely present in the previous implementation.openmeter/entitlement/metered/reset_test.go (3)
325-335: Updated test to use new balance structureThe test has been properly updated to reflect changes in the balance API, now accessing balances through
creditBalance.Snapshot.Balancesrather than directly throughcreditBalance.Balances.
397-407: Updated test to use new balance structureTests are correctly updated to reflect the new structure of the balance data returned by
GetBalanceAt.
469-479: Updated test to use new balance structureThe test is properly updated to access balance data through the new structure, maintaining consistency with the API changes.
openmeter/credit/engine/run_test.go (4)
129-129: Updated history access pattern.The code now uses the new
Segments()method to access history data instead of directly accessing the underlying array. This change aligns with the structural modifications in the History field of the RunResult struct.
311-315: History access pattern updated consistently.The history access pattern has been correctly updated to use the
Segments()method throughout the test cases. This ensures consistency with the new data structure.
345-348: Properly migrated to new History access pattern.All test assertions have been properly migrated to access history segments through the
Segments()method.
798-876: History accessor pattern consistently applied.The changes consistently apply the new pattern across all test assertions, ensuring that the tests align with the underlying implementation changes in the History data structure.
openmeter/entitlement/metered/grant_owner_adapter.go (2)
131-134: Added entitlement parsing with proper error handling.Good addition of entitlement parsing with appropriate error handling to ensure invalid entitlements don't cause runtime issues.
149-162: Enhanced period calculation logic.The new logic correctly differentiates between the first usage period and subsequent periods, which helps ensure consistency with balance and grant information. This aligns with the PR objective of ensuring usage information is queried only once.
The implementation:
- Calculates the first period using the original anchor and activation time
- Checks if the current period matches the first period
- Returns the appropriate start time based on the period comparison
openmeter/entitlement/metered/utils_test.go (2)
46-47: Added creditConnector to dependencies struct.This addition aligns with the modifications in the balance retrieval logic elsewhere in the codebase.
157-158: Including creditConnector in returned dependencies.Properly included the creditConnector in the returned dependencies structure, ensuring it's available for tests that need access to the updated balance retrieval functionality.
openmeter/credit/engine/reset_test.go (5)
102-103: Updated history access pattern.The code now uses the
Segments()method to access history data rather than directly accessing the array, consistent with the structural changes in the History field of the RunResult struct.
104-116: Consistently updated history access pattern.All assertions have been consistently updated to use the
Segments()method for accessing history segments, ensuring proper alignment with the updated data structure.
152-167: History access pattern updated consistently.The method for accessing history segments has been properly updated throughout the assertions in this test case, maintaining consistency with the new data structure approach.
194-198: History accessor updated correctly.Length check and termination reason assertions properly migrated to use the new
Segments()method.
227-231: History assertions updated with detailed error messages.The test includes a detailed error message in the assertion, which is helpful for debugging if the test fails. The termination reason checks also use the new
Segments()method consistently.test/entitlement/regression/scenario_test.go (2)
345-349: Improved approach to testing grant deduction based on priority.The added usage event with its associated comment provides clarity on how the priority-based deduction should work, making the test more comprehensive.
354-357: Good enhancement for test accuracy.Storing the void time in a variable and adding a usage event before voiding the grant is a good approach to test the correct temporal ordering of operations. This helps verify that the system correctly handles usage events that occur before a grant is voided.
openmeter/credit/engine/history.go (2)
69-76: Well-designed snapshot method addition.This new
ToSnapshotmethod nicely encapsulates the conversion from a history segment to a snapshot, improving code organization and reusability.
78-99: Good change from pointer to value return type.Switching from returning a pointer to returning a value type for
NewGrantBurnDownHistoryis a good practice that makes the function more predictable and reduces the need for nil checks.openmeter/entitlement/metered/lateevents_test.go (2)
31-55: Well-designed test infrastructure for simulating late events.The
inconsistentCreditConnectorimplementation is a clever way to inject events before and after the balance retrieval calls, allowing the test to verify consistency in the face of late-arriving events.
57-230: Comprehensive test for balance consistency with late events.This thorough test case verifies that balance calculations remain consistent even when events arrive late, directly addressing the PR's objective of maintaining consistency between balance and usage information.
The assertion on line 229 effectively verifies that the balance, usage, and overage values correctly sum to the total grant amount, which is a crucial invariant.
openmeter/credit/engine/run.go (4)
41-41: Improved variable naming for clarity.Renaming
historytohistorySegmentsprovides better context about the variable's contents and purpose.
58-58: Updated history access pattern.Changing from direct append to using
runRes.History.Segments()shows a more structured approach to accessing history segments, aligning with the new GrantBurnDownHistory design.
77-81: Enhanced error handling for history creation.Adding proper error handling when creating the grant burn down history improves robustness and makes debugging easier by providing specific error messages.
207-211: Consistent error handling pattern.Applying the same error handling pattern for history creation in both methods maintains consistency throughout the codebase.
openmeter/credit/balance.go (4)
26-31: Interface changes align with PR objectives.The interface has been revised to use new methods that return more comprehensive
engine.RunResultdata instead of simple snapshots, aligning with the goal to ensure consistency between balance and usage data.
38-46: Time rounding logic ensures completeness.The rounding logic ensures that partial usage in the last minute is included in calculations by rounding up to the next minute if needed.
98-102: Important grant filtering logic.This code ensures that inactive grants at query time are excluded from results, which is consistent with the handling in regular snapshotting code as noted in your previous comments.
140-153: Initial balance calculation approach is efficient.Using
GetBalanceAtto obtain the starting snapshot for the period and then continuing calculation from that point is a good optimization pattern.openmeter/entitlement/metered/balance.go (5)
58-62: Time rounding is now consistent with balance connector.The rounding logic ensures partial usage in the last minute is included and correctly notes this won't affect usage period boundaries.
74-83: Good adaptation to new interface with proper error handling.The code now uses the new
GetBalanceForPeriodmethod with appropriate period parameters and correctly handlesOwnerNotFoundErrorby converting it to an entitlement-specific error.
87-89: Updated result field access.The code correctly adapts to the new structure by accessing balance, usage, and overage from their appropriate locations in the result.
243-243: Adaptation to new history structure.Correctly accessing segments from the new history structure in the result.
346-346: Return value adaptation.Returning the history directly from the result is consistent with the interface changes.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
9284c3a to
047f1ba
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (14)
openmeter/credit/adapter/grant.go(1 hunks)openmeter/credit/balance.go(5 hunks)openmeter/credit/engine/engine.go(1 hunks)openmeter/credit/engine/history.go(2 hunks)openmeter/credit/engine/reset_test.go(4 hunks)openmeter/credit/engine/run.go(4 hunks)openmeter/credit/engine/run_test.go(6 hunks)openmeter/credit/helper.go(1 hunks)openmeter/entitlement/metered/balance.go(4 hunks)openmeter/entitlement/metered/grant_owner_adapter.go(2 hunks)openmeter/entitlement/metered/lateevents_test.go(1 hunks)openmeter/entitlement/metered/reset_test.go(10 hunks)openmeter/entitlement/metered/utils_test.go(2 hunks)test/entitlement/regression/scenario_test.go(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
openmeter/entitlement/metered/lateevents_test.go (1)
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: CI
- GitHub Check: Analyze (go)
🔇 Additional comments (46)
openmeter/credit/engine/engine.go (1)
31-31: Type change enhances history structure.The
Historyfield is now a singleGrantBurnDownHistoryobject rather than an array of segments. This structured approach centralizes history management and provides better encapsulation of history segments.openmeter/credit/helper.go (1)
217-217: Changed to use the newSegments()method.Updated to access history segments through the new method, which aligns with the structural changes to the
Historyfield in theRunResultstruct.openmeter/credit/adapter/grant.go (1)
177-177: Added condition to include grants effective at period end.This change ensures that grants becoming effective exactly at the end time of the period are correctly included in the query results, which is necessary for consistent balance calculations.
openmeter/credit/engine/reset_test.go (1)
102-102: Updated to use the newSegments()method in tests.All test assertions now access history segments through the
Segments()method instead of directly. This change maintains consistency with the structural changes to theHistoryfield in theRunResultstruct.Also applies to: 105-107, 110-110, 113-115, 152-152, 155-158, 161-161, 164-166, 194-194, 196-197, 227-227, 229-230
openmeter/entitlement/metered/reset_test.go (3)
324-334: API usage update looks goodThe test properly adopts the new
GetBalanceAtmethod instead ofGetBalanceOfOwnerand correctly accesses the balance information via theSnapshotfield.
397-406: Consistent API usageThe test consistently follows the pattern of using
GetBalanceAtand accessing values throughSnapshot.Balances.
469-478: API usage consistently applied across test casesGood job maintaining consistency across all test cases with the new approach to accessing balance data.
openmeter/entitlement/metered/utils_test.go (2)
46-46: Added creditConnector to dependencies structGood addition of the
creditConnectorfield to the dependencies struct to support the updated API usage in the tests.
157-157: Updated setup for creditConnectorThe dependencies return statement properly includes the new
creditConnectorreference, keeping the code consistent with struct definition.openmeter/credit/engine/run_test.go (1)
129-129: Migration to Segments() method for accessing historyThe test has been properly updated to use the new
Segments()method for accessing history data instead of directly accessing the History field. This change is consistent throughout the file and maintains the test assertions correctly.Also applies to: 311-314, 345-348, 439-445, 866-876
openmeter/entitlement/metered/grant_owner_adapter.go (2)
131-134: Added proper parsing and error handlingGood addition of code to parse the entitlement into a
meteredvariable with appropriate error handling.
149-162: Enhanced logic for first usage period calculationThis is a meaningful enhancement that correctly distinguishes between the first usage period and subsequent periods. The code:
- Calculates the first period using the original anchor and activation time
- Compares if current period equals first period
- Returns measurement start time for the first period, otherwise returns the current period start
The implementation is well-commented and maintains the original functionality while adding the new logic.
test/entitlement/regression/scenario_test.go (2)
345-349: Good use of comments to clarify expected behaviorThe added comments help developers understand the test logic: this usage event is expected to be deducted from grant 2 due to priority rules. Clear comments like these improve test readability and maintainability.
354-357: Good refactoring for more reliable testsStoring the void time in a variable and adding a usage event before voiding the grant provides a more consistent testing approach. This aligns with the PR goal of ensuring usage information for a period is queried only once.
openmeter/entitlement/metered/lateevents_test.go (2)
32-45: Well-structured mock for testing late eventsThe
inconsistentCreditConnectoris a good approach for testing how the system handles events that arrive during balance calculation. By adding events before and after the actual balance query, this effectively tests the consistency mechanisms.I'm leveraging your team's established pattern of using package-scoped variables like
meterSlugin test files.
57-231: Comprehensive test for balance calculation consistencyThis test thoroughly verifies that balance and usage values remain consistent even when late events arrive during calculation. This directly addresses the PR objective of utilizing history calculation to ensure usage information is queried only once.
The test structure follows good practices:
- Clear setup with helper functions
- Proper cleanup with
deferstatements- Explicit assertions that validate the balance calculation consistency
openmeter/credit/engine/history.go (2)
69-76: Useful addition of ToSnapshot methodAdding the
ToSnapshotmethod toGrantBurnDownHistorySegmentprovides a clean way to convert a history segment to a snapshot. This supports the PR goal of modifying the balance functionality to utilize history calculation.
78-99: Good refactoring from pointer to value returnChanging
NewGrantBurnDownHistoryto return a value instead of a pointer makes the code more consistent and aligns with modern Go practices for small structs. The error handling is also properly updated to return a zero value instead of nil.openmeter/credit/engine/run.go (4)
41-42: Improved variable namingRenaming
historytohistorySegmentsmakes the code more descriptive and clarifies that this variable holds segments rather than the complete history object.
57-59: Updated history segments handlingThis change properly uses the new
Segments()method to access the history segments, aligning with the structural changes in the history implementation.
77-81: Proper error handling addedAdding error handling for
NewGrantBurnDownHistoryimproves robustness by ensuring that any issues with history creation are properly caught and reported.
207-211: Consistent error handling patternThe error handling for
NewGrantBurnDownHistoryfollows the same pattern as in the mainRunmethod, ensuring consistency throughout the codebase.openmeter/entitlement/metered/balance.go (5)
58-62: Verify rounding-up approach for minute boundary.
These lines force the timestamp to the next minute boundary when it's not already aligned. Ensure this logic aligns with the intended business rule (i.e., capturing partial usage in the last minute).
74-82: Use of GetBalanceForPeriod and error path looks good.
The new code properly translates anOwnerNotFoundErrorinto anentitlement.NotFoundError, maintaining a clear hierarchy of errors.
87-89: Field usage aligns with the new engine result.
The usage and overage fields are now sourced from theRunResultstruct. Looks consistent with the updated design.
243-243: Segments retrieval aligns with the updated History struct.
Accessing segments fromhistoryRes.History.Segments()is consistent with the new engine approach.
346-346: Returning the final computed windows and History looks correct.
This ensures both the per-window breakdown and the overall burn-down history are provided to the caller.openmeter/credit/balance.go (19)
26-33: New interface methods provide clearer period-based balance retrieval.
Replacing the old methods withGetBalanceAt,GetBalanceForPeriod, and the updatedResetUsageForOwnersignature is a solid step toward unifying the logic.
38-42: Implementation for GetBalanceAt appears correct.
The approach to round up to the nearest minute and maintain a defaultengine.RunResultfor error scenarios is reasonable. Double-check off-by-one minute edge cases.
51-51: No issues with immediate error return.
Graceful fallback todefensures consistency in the return type under error conditions.
62-62: Same pattern of returning a default on error.
This matches the overall error-handling approach.
67-67: No further concerns here.
73-73: No further concerns here.
81-81: No further concerns here.
95-97: No major issues with the error return path.
98-101: Ensure inactive grant removal is accurate.
Double-check thatremoveInactiveGrantsFromSnapshotAtcorrectly identifies grants that should remain active at the given time.
111-111: Error return consistency maintained.
115-115: Final return of run result is aligned with the new flow.
No issues identified.
119-124: Method-level documentation and definitions look consistent.
Declaring a defaultengine.RunResultbefore the logic is consistent with the rest of the file.
125-126: Rounding up the period’s end time.
As with the other rounding logic, verify that this approach captures the complete usage in that final minute.
132-132: No further concerns here.
137-137: No further concerns here.
141-148: Integration with GetBalanceAt and grants retrieval.
These calls look appropriate for retrieving the starting snapshot and grants required to compute the period usage.
152-156: Snapshot update for grants becoming active exactly at the start.
Filling in missing grants ensures the snapshot stays consistent with the period’s actual entitlements.
174-174: No further concerns for error handling here.
177-177: Final return of result.
This wraps up the period-based calculation correctly.
There was a problem hiding this comment.
Actionable comments posted: 4
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (1)
openmeter/credit/balance.go(5 hunks)
🔇 Additional comments (23)
openmeter/credit/balance.go (23)
38-38: Implementation introduced.The new method signature for
GetBalanceAtis clear; no issues identified.
51-51: Error return looks good.Returning an empty RunResult plus the encountered error is consistent with the existing pattern.
61-62: Error handling is consistent.Looks good; the context-specific error message provides clarity.
67-67: Error handling is consistent.No issues spotted; message is descriptive.
71-71: Grant listing logic.The repository call for active grants in the specified time range is straightforward.
73-73: Error handling is consistent.No issues here; consistent error messaging.
81-81: Return on engine build error.Looks good; returning immediately on engine build failure is appropriate.
95-96: Balance calculation error fallback.Checks and returns are properly handled.
98-101: Ensuring snapshot consistency by removing inactive grants.This is a sensible addition. It helps maintain accurate snapshot data.
111-111: Snapshot error path.Consistent handling of snapshot engine errors.
115-115: Successful return.Looks correct; returning the computed result.
122-122: Repeated default result pattern.Same observation as before: consider inlining the default return instead of defining a variable.
131-132: Reset timeline retrieval.Error handling is consistent and descriptive.
137-137: Describing owner error path.Looks fine; thorough error message.
141-143: Fetching initial snapshot for period start.Calling
GetBalanceAtfrom withinGetBalanceForPeriodis logical; no concerns.
147-147: Grant retrieval extended range.Correctly retrieves grants spanning the entire period.
149-149: Error fallback.No issues; consistent usage.
152-153: Snapshot extraction.Extracting the starting snapshot from the previous run result is straightforward.
156-156: Populate snapshot with newly active grants.Appropriate logic to ensure completeness of the snapshot.
160-160: Engine build error fallback.Same consistent pattern; no issues spotted.
167-167: Passing snapshot in RunParams.Implementation follows established pattern.
174-174: Final balance error case.Good coverage with an informative error message.
177-177: Return final engine result.End of method logic is clear and consistent.
…ata is consistent
721067b to
85058b7
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
openmeter/credit/balance.go (2)
38-41: Consider adding more context to method documentation.While the documentation comment explains the method's purpose, it would be helpful to add information about edge cases, performance characteristics, or why calculating from the latest valid snapshot is important for users of this interface.
118-119: Function documentation could be more specific.The comment describes what the function does but doesn't explain when to use this method versus
GetBalanceAtor what "exactly match the provided period" means in practical terms for callers.openmeter/credit/engine/history.go (1)
78-78: Consider method receiver consistencyThe return type of
NewGrantBurnDownHistoryhas been changed from a pointer to a value, but the methods onGrantBurnDownHistory(lines 105-120) still use pointer receivers. This creates inconsistency in how the struct is handled.If the intent is to use value semantics, consider updating the method receivers:
-func (g *GrantBurnDownHistory) Segments() []GrantBurnDownHistorySegment { +func (g GrantBurnDownHistory) Segments() []GrantBurnDownHistorySegment {Or if pointer semantics are preferred (for performance with larger structs):
-func NewGrantBurnDownHistory(segments []GrantBurnDownHistorySegment) (GrantBurnDownHistory, error) { +func NewGrantBurnDownHistory(segments []GrantBurnDownHistorySegment) (*GrantBurnDownHistory, error) {This would ensure consistent handling across the codebase.
Also applies to: 94-94, 98-98
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
openmeter/credit/adapter/grant.go(1 hunks)openmeter/credit/balance.go(5 hunks)openmeter/credit/engine/engine.go(1 hunks)openmeter/credit/engine/history.go(2 hunks)openmeter/credit/engine/reset_test.go(4 hunks)openmeter/credit/engine/run.go(4 hunks)openmeter/credit/engine/run_test.go(6 hunks)openmeter/credit/helper.go(1 hunks)openmeter/entitlement/metered/balance.go(4 hunks)openmeter/entitlement/metered/grant_owner_adapter.go(2 hunks)openmeter/entitlement/metered/lateevents_test.go(1 hunks)openmeter/entitlement/metered/reset_test.go(10 hunks)openmeter/entitlement/metered/utils_test.go(2 hunks)test/entitlement/regression/scenario_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (9)
- openmeter/credit/engine/engine.go
- openmeter/credit/adapter/grant.go
- openmeter/credit/helper.go
- openmeter/entitlement/metered/utils_test.go
- openmeter/credit/engine/run.go
- openmeter/entitlement/metered/balance.go
- openmeter/credit/engine/run_test.go
- openmeter/entitlement/metered/reset_test.go
- openmeter/credit/engine/reset_test.go
🧰 Additional context used
🧠 Learnings (1)
openmeter/entitlement/metered/lateevents_test.go (1)
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
🔇 Additional comments (11)
openmeter/credit/balance.go (4)
26-31: Interface updates improve clarity with explicit period-based methods.The updated
BalanceConnectorinterface now uses explicit methods for time-specific balance retrieval (GetBalanceAtandGetBalanceForPeriod), replacing the less descriptive methods. This makes the API more intuitive and aligns with the actual use cases.
98-102: Ensuring consistency by filtering inactive grants.This new code handles an important edge case by removing grants that are no longer active at the query time, which is required for treating RunResults as virtual snapshots.
123-126: Time rounding logic duplicated between methods.The time rounding logic appears in both
GetBalanceAtandGetBalanceForPeriod. Consider extracting this to a helper function to avoid duplication and make future maintenance easier.
139-143: Good reuse of existing functionality.Using
GetBalanceAtto establish the starting point for period calculation is an efficient approach that minimizes code duplication and ensures consistency between the two methods.test/entitlement/regression/scenario_test.go (1)
345-357: Test improvements with more realistic usage scenarios.The test has been improved by adding actual usage events instead of manipulating snapshots directly. This approach better mimics real-world usage patterns and provides a more accurate test of the system's behavior. The added comments explaining the expected grant deduction behavior also improve code readability.
openmeter/entitlement/metered/grant_owner_adapter.go (1)
131-162: Enhanced period calculation logic correctly handles first usage period.This change improves the accuracy of usage period calculations by correctly handling the first usage period separately from subsequent periods. The implementation now properly distinguishes between:
- The first period (when the entitlement becomes active) - returning the measurement start time
- Subsequent periods - returning the current period's start time
This ensures that usage is correctly measured from when the entitlement becomes active rather than from the period start for the first period.
openmeter/entitlement/metered/lateevents_test.go (3)
31-55: Well-designed test mock for simulating late events.The
inconsistentCreditConnectorimplementation is a good approach for testing late event handling. By adding events both before and after the balance calculation, it simulates the real-world scenario where events might arrive late or out of order.
57-89: Test setup is thorough and well-structured.The test setup code defines clear helper functions for creating features and entitlements, making the test readable and maintainable. The use of a yearly interval in the default setup is a good choice for testing as it minimizes the chance of period boundaries affecting the test.
187-230: Test validates key business logic requirement.This test effectively validates that the balance and usage calculations remain consistent even when events arrive late. The assertion checking that
g1.Amount == entBalance.UsageInPeriod + entBalance.Balance - entBalance.Overageis particularly valuable as it ensures the core business logic remains correct regardless of event timing.openmeter/credit/engine/history.go (2)
69-76: Clean implementation of ToSnapshot methodThe addition of the
ToSnapshotmethod to convert a segment's initial state into abalance.Snapshotis well-implemented. This facilitates consistency with the balance interfaces mentioned in the PR objectives.
78-99:Details
✅ Verification successful
Verify all callers have been updated
The change from returning a pointer to returning a value requires all callers to be updated accordingly. Please verify that all code that calls
NewGrantBurnDownHistoryhas been properly updated to handle the value return instead of a pointer.
🏁 Script executed:
#!/bin/bash # Find all callers of NewGrantBurnDownHistory echo "Searching for callers of NewGrantBurnDownHistory:" rg "NewGrantBurnDownHistory\(" --type goLength of output: 458
Action Required: Confirmed Caller Updates
All instances of
NewGrantBurnDownHistoryhave been verified. The two call sites inopenmeter/credit/engine/run.goare updated to handle a value return rather than a pointer, and no pointer-based accesses (e.g., using->) are detected.
- Caller in
openmeter/credit/engine/run.gousinghistory, err := NewGrantBurnDownHistory(historySegments)- Caller in
openmeter/credit/engine/run.gousinghistory, err := NewGrantBurnDownHistory(segments)No further changes are required.
Overview
Changes
metered/balanceto usecredit's history calculation. This way period's usage information is only queried once & is consistent with balance and grant information.Summary by CodeRabbit
New Features
Tests