Repository navigation
Persisting Usage in Snapshots (History Rewrite Part III) - #2406
Conversation
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughThis pull request introduces a new entitlement configuration that includes a grace period, and it propagates this configuration across multiple components. Method signatures, constructors, and service dependencies are updated to accept a configuration struct. Additionally, a new usage tracking mechanism is added to balance snapshots by introducing a new type to record usage metrics. The changes include updates to database schemas, ORM layer functions, and test cases, as well as associated SQL migrations for the new “usage” column. Changes
📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (60)
✨ 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 (
|
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (2)
openmeter/credit/balance.go (2)
41-108: 🛠️ Refactor suggestionImplementation of
GetBalanceSinceSnapshot.
This method cleanly computes the balance from the last snapshot. The flow looks logical, with well-structured error handling.
- Consider removing or addressing the
TODOabout artificial history breakpoints so these tasks don’t get lost.- Verify that partial usage periods are handled correctly if
snap.Atis very close toat.Do you want me to open a new issue to track the artificial history breakpoints TODO item?
190-314: 🛠️ Refactor suggestionComprehensive usage reset flow.
Reusing the engine to compute final usage before resetting is logical. A couple of suggestions:
- Check for concurrency race conditions when resets happen in quick succession.
- Verify thorough testing for edge cases, like resets near the boundary of the usage period.
🧹 Nitpick comments (9)
openmeter/credit/connector.go (1)
24-36: Consider adding basic field validation inCreditConnectorConfig.
All fields in this config struct are exported and may be set to nil or misconfigured. For robustness, consider validating critical references (e.g., repos, services) to avoid runtime panics.func NewCreditConnector(cfg CreditConnectorConfig) CreditConnector { + if cfg.GrantRepo == nil || cfg.BalanceSnapshotService == nil || cfg.TransactionManager == nil { + panic("CreditConnectorConfig: missing mandatory dependencies") + } return &connector{ CreditConnectorConfig: cfg, } }openmeter/credit/balance/usage.go (1)
22-37: Config struct is flexible but ensure concurrency safety.
Storing function references likeDescribeOwner,GetDefaultParamsis convenient for testing, but check that concurrency scenarios (parallel calls) are either unlikely or handled.openmeter/credit/balance/service.go (1)
21-30: Config-driven approach is consistent but watch for nil fields.
SnapshotServiceConfigreferences external connectors and repos. Similar to the credit connector config, consider validating these dependencies if usage in production demands stability.openmeter/entitlement/metered/utils_test.go (1)
36-47: Consider modularizing the dependencies struct if it grows further.
These new fields align well with the transition to a service-based architecture. However, if this dependencies struct continues to expand, you might consider modularizing fields or using more specific test fixtures to avoid overly large dependency objects.test/entitlement/regression/framework_test.go (1)
40-43: Expanded dependencies struct.
The updated fields forGrantRepo,BalanceSnapshotService, andGrantConnectorappear consistent. Just be mindful of potential growth if more dependencies are added.openmeter/credit/balance.go (2)
35-36: GetLastValidSnapshotAt interface extension.
This looks straightforward. Ensure all callers handle potential “no snapshot found” scenarios gracefully.
130-188: Ensure consistent rounding approach across methods.
GetBalanceForPeriodalso rounds the period to the next minute. Consider centralizing this rounding logic to avoid duplication or divergence over time.openmeter/credit/helper.go (2)
26-26: Consider using structured logging.
Usingm.Logger.DebugContext(ctx, "message", "owner", owner.ID, "time", at)would be more consistent with key-value logs elsewhere in this file.- m.Logger.Debug(fmt.Sprintf("no saved balance found for owner %s before %s, calculating from start of time", owner.ID, at)) + m.Logger.DebugContext(ctx, "no saved balance found for owner", + "owner", owner.ID, + "before", at, + "detail", "calculating from start of time", + )
87-87: Minor grammatical fix in comment.- // We build a custom UsageQuerier for our usecase here. The engine should only every query the one owner we fetched above. + // We build a custom UsageQuerier for our use case here. The engine should only ever query the one owner we fetched above.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (44)
app/common/entitlement.go(1 hunks)app/config/config.go(1 hunks)app/config/config_test.go(2 hunks)app/config/entitlements.go(1 hunks)cmd/balance-worker/wire_gen.go(2 hunks)config.example.yaml(1 hunks)openmeter/billing/worker/subscription/sync_test.go(2 hunks)openmeter/credit/adapter/balance_snapshot.go(2 hunks)openmeter/credit/adapter/transaction.go(1 hunks)openmeter/credit/balance.go(13 hunks)openmeter/credit/balance/balance.go(1 hunks)openmeter/credit/balance/repository.go(1 hunks)openmeter/credit/balance/service.go(1 hunks)openmeter/credit/balance/usage.go(1 hunks)openmeter/credit/connector.go(1 hunks)openmeter/credit/engine/history.go(2 hunks)openmeter/credit/engine/reset_test.go(5 hunks)openmeter/credit/engine/run.go(4 hunks)openmeter/credit/engine/run_test.go(2 hunks)openmeter/credit/grant.go(8 hunks)openmeter/credit/helper.go(5 hunks)openmeter/ent/db/balancesnapshot.go(4 hunks)openmeter/ent/db/balancesnapshot/balancesnapshot.go(2 hunks)openmeter/ent/db/balancesnapshot/where.go(1 hunks)openmeter/ent/db/balancesnapshot_create.go(4 hunks)openmeter/ent/db/balancesnapshot_update.go(2 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(10 hunks)openmeter/ent/schema/balance_snapshot.go(1 hunks)openmeter/entitlement/metered/balance.go(1 hunks)openmeter/entitlement/metered/balance_test.go(6 hunks)openmeter/entitlement/metered/lateevents_test.go(4 hunks)openmeter/entitlement/metered/reset_test.go(2 hunks)openmeter/entitlement/metered/utils_test.go(3 hunks)openmeter/registry/builder/entitlement.go(3 hunks)openmeter/subscription/testutils/customer.go(3 hunks)openmeter/subscription/testutils/service.go(3 hunks)test/app/stripe/testenv.go(3 hunks)test/app/testenv.go(4 hunks)test/billing/suite.go(3 hunks)test/customer/testenv.go(3 hunks)test/entitlement/regression/framework_test.go(4 hunks)tools/migrate/migrations/20250307151454_balance-snapshot-usage.down.sql(1 hunks)tools/migrate/migrations/20250307151454_balance-snapshot-usage.up.sql(1 hunks)
🔇 Additional comments (123)
tools/migrate/migrations/20250307151454_balance-snapshot-usage.up.sql (1)
1-2: Database schema change looks goodThe migration adds a new nullable JSON column
usageto thebalance_snapshotstable, which aligns with the PR objective of incorporating usage information into snapshots.tools/migrate/migrations/20250307151454_balance-snapshot-usage.down.sql (1)
1-2: Down migration is correctly implementedThe down migration properly drops the
usagecolumn to revert the schema change if needed.config.example.yaml (1)
57-58: Configuration change matches PR objectivesAdding the
entitlements.gracePeriodconfiguration withP1Daligns with the PR objective of reducing the grace period from one week to one day, allowing late events to be included in snapshots for up to one day.app/config/config_test.go (2)
17-17: Imported package appropriately addedThe
isodatepackage is correctly imported to support the new entitlements configuration with ISO 8601 duration format.
139-141: Test configuration updated correctlyThe test expectations have been appropriately updated to include the new
Entitlementsconfiguration with theGracePeriodset toP1D, which maintains consistency with the example configuration and ensures tests will pass with the new configuration structure.openmeter/ent/schema/balance_snapshot.go (1)
33-35: Good addition of usage field to support snapshots historyThe new JSON field for storing usage data in snapshots is implemented correctly using the appropriate field type and configuration options. Making it immutable and optional aligns with the snapshot pattern.
openmeter/ent/db/balancesnapshot/balancesnapshot.go (2)
29-30: Good addition of the usage field constantThe field constant definition follows the established pattern in the codebase.
59-59: Good addition of usage field to ColumnsThe field is correctly added to the Columns slice, making it available for database operations.
app/config/config.go (1)
186-186: Good integration of entitlements configurationThe addition of entitlements configuration follows the pattern used for other components and supports the grace period changes mentioned in the PR.
openmeter/credit/engine/run_test.go (3)
184-190: Good implementation of snapshot usage testingThis test setup correctly creates a
SnapshottedUsageinstance with appropriate values to test usage persistence in snapshots.
196-196: Good integration of usage in starting snapshotThe test correctly includes the usage field in the starting snapshot parameters.
208-208: Good verification of usage persistenceThe assertion correctly verifies that the original usage information is preserved in the result snapshot, with a helpful comment explaining the expected behavior.
openmeter/ent/db/balancesnapshot/where.go (1)
358-366: Implementation for the new Usage field query predicatesThese new functions allow for querying whether the "usage" field is null or not in the database. This is a consistent addition following the same pattern as other nullable fields in the file (e.g.,
DeletedAtIsNil).openmeter/credit/grant.go (4)
36-36: Field naming convention updatesThe field referencing has been updated from
m.grantRepotom.GrantRepo, which appears to be part of a broader refactoring to standardize naming conventions for repository/service dependencies.
44-44: Consistent renaming of service referencesThe references to
m.ownerConnectorhave been updated tom.OwnerConnectorthroughout the file. This is consistent with the other dependency renaming in this PR.Also applies to: 53-53, 62-62, 128-128, 133-133
84-84: Repository to Service upgrade for balance snapshotsThe references have been changed from
m.balanceSnapshotRepotom.BalanceSnapshotService, suggesting an architectural change from direct repository access to using a service wrapper, which aligns with the PR objectives of introducing a service wrapper around the repository.Also applies to: 145-145
138-139: New property reference for granularityThe code now uses
m.Granularityto truncate the timestamp, which likely comes from the new configuration structure. This ensures consistent time handling across the system.test/app/stripe/testenv.go (1)
129-131: Grace period configuration changeThe grace period has been reduced from one week to one day (
"P1D") as specified in the PR objectives. This ensures that late events can be included in snapshots for up to one day, which is consistent with the PR's goal to modify snapshot behavior.openmeter/ent/db/balancesnapshot_update.go (1)
127-129: Support for clearing the new Usage fieldThese additions handle the case when the Usage field needs to be cleared, ensuring proper SQL operations. The implementation follows the same pattern as the existing DeletedAt field clearing, maintaining code consistency.
Also applies to: 276-278
openmeter/credit/balance/balance.go (3)
71-74: Good addition of the SnapshottedUsage type.This new type provides a clear way to track both usage metrics and their timestamps together, which aligns with the PR objective of enhancing snapshots with usage information.
76-78: Well-implemented utility method.The
IsZero()method provides a clean way to check if a usage record is effectively empty. This will be useful for conditional logic elsewhere in the codebase.
81-81: Good integration of the Usage field into the Snapshot struct.The addition of the
Usagefield to theSnapshotstruct properly integrates the new usage tracking functionality with the existing balance snapshot functionality.openmeter/ent/db/balancesnapshot.go (4)
35-36: Good addition of the Usage field to the BalanceSnapshot struct.The field is properly defined with appropriate JSON tags and pointer type, which allows for null values in the database.
74-74: Good update to scanValues for the new field.The scanValues method is correctly updated to handle the new Usage field, ensuring it's properly processed when retrieved from the database.
144-151: Well-implemented assignValues logic for the Usage field.The code correctly handles unmarshaling the Usage field from a byte slice, with proper error handling and nil checks. This ensures the field is correctly populated from database values.
231-233: Properly updated String method.The String method is correctly updated to include the new Usage field, ensuring it's represented in string representations of the BalanceSnapshot entity.
openmeter/subscription/testutils/service.go (1)
80-82: Good implementation of the grace period configuration.The code properly initializes the EntitlementsConfiguration with a grace period of "P1D" (1 day), which aligns with the PR objective of reducing the grace period from one week to one day to ensure that late events can be included in snapshots for up to one day.
openmeter/ent/db/balancesnapshot_create.go (3)
87-91: Well-implemented SetUsage method.The SetUsage method follows the pattern of other setter methods in the file and properly integrates with the mutation system.
248-251: Good handling of the Usage field in createSpec.The code properly handles setting the Usage field in the create specification and node, following the pattern used for other fields.
386-388: Consistent handling of Usage field in update logic.The code correctly handles the Usage field in the update logic for both single and bulk operations, ensuring it's properly ignored when appropriate in upsert operations.
Also applies to: 652-654
test/customer/testenv.go (2)
9-9: New imports for configuration and ISO date handlingThese imports support the new entitlements configuration with grace period functionality.
Also applies to: 20-20
87-89: Grace period reduced from 1 week to 1 dayThe EntitlementsConfiguration is initialized with a grace period of "P1D" (1 day), aligning with the PR objective to reduce the grace period from one week to one day. This change ensures that late events can be included in snapshots for up to one day.
openmeter/credit/balance/repository.go (1)
13-13: Helpful documentation clarifies potential data limitationsThis comment provides important information to consumers of the
GetLatestValidAtmethod, explicitly stating that the returned Snapshot might not contain usage data. This aligns with the PR objective of incorporating usage information in snapshots.cmd/balance-worker/wire_gen.go (2)
136-136: Configuration extraction for entitlementsExtracts the entitlements configuration from the main configuration object for clearer usage in dependency injection.
181-187: Updated EntitlementOptions with configuration structAdded the EntitlementsConfiguration field to the EntitlementOptions struct, properly propagating the configuration to the entitlement registry. This change supports the PR objective of enhancing snapshots with usage information.
app/common/entitlement.go (1)
30-36: Dependency injection updated with entitlements configurationThe EntitlementOptions struct now includes the EntitlementsConfiguration parameter, ensuring that the grace period configuration is properly passed to the registry builder. This change supports consistent handling of grace periods across the application.
test/billing/suite.go (1)
19-19: Imported necessary packages and added EntitlementsConfiguration with a 1-day grace period.The changes correctly implement the grace period reduction from one week to one day as mentioned in the PR objectives. This configuration is now passed to the entitlement registry during test suite setup.
Also applies to: 39-39, 106-108
openmeter/subscription/testutils/customer.go (1)
11-11: Configured EntitlementsConfiguration with consistent grace period.These changes ensure that customer tests use the same one-day grace period, maintaining consistency with the changes in the main test suite.
Also applies to: 22-22, 74-76
test/app/testenv.go (1)
12-12: Applied EntitlementsConfiguration consistently across test environments.The grace period configuration is properly applied in both the
NewTestEnvandInitBillingServicefunctions, ensuring consistent behavior throughout testing.Also applies to: 33-33, 106-108, 238-240
openmeter/entitlement/metered/balance.go (2)
73-82: Improved entitlement balance calculation using snapshots instead of periods.The balance calculation logic has been refactored to first retrieve the last valid snapshot at a given time and then calculate the balance since that snapshot. This approach aligns with the PR objective of enhancing snapshot functionality to incorporate usage information.
The error handling has also been improved with more specific error messages that indicate which operation failed.
87-87: Updated usage calculation to use the snapshot's usage data directly.This change ensures that the usage information accurately reflects what's stored in the snapshot, which is consistent with the PR objective of ensuring snapshots contain accurate usage information alongside balance data.
openmeter/credit/adapter/transaction.go (1)
42-42: Return type updated from interface to concrete typeThe function now returns a pointer to
balanceSnapshotRepoinstead of thebalance.SnapshotRepointerface. This change aligns with the service wrapper approach introduced in this PR for incorporating usage information in snapshots.app/config/entitlements.go (4)
13-15: New configuration struct for entitlementsThis introduces the EntitlementsConfiguration struct with a GracePeriod field to support the grace period reduction from one week to one day mentioned in the PR.
19-25: Proper validation for the GracePeriod fieldGood validation implementation that ensures the GracePeriod is both provided and valid.
30-37: Robust GetGracePeriod method with fallbackThis method properly handles error cases by logging the parsing error and falling back to a default value of 1 day.
39-42: Default configuration for grace periodSets the default grace period to "P1D" (1 day), which aligns with the PR's objective of reducing the grace period to ensure that late events can be included in snapshots for up to one day.
openmeter/credit/engine/reset_test.go (5)
81-84: New Usage tracking in snapshotsAdding the SnapshottedUsage struct to StartingSnapshot allows for tracking usage since the last reset, supporting the PR's objective of enhancing snapshots with usage information.
105-107: Test assertions for usage data after resetThese assertions verify that usage data is correctly reset after a reset operation, ensuring the snapshot reflects zero usage and updates the Since timestamp to the reset time.
184-187: Test setup for usage tracking without resetThis initializes a SnapshottedUsage struct with existing usage data to test the scenario where no reset occurs.
207-209: Test assertions for continuous usage trackingThese assertions verify that when no reset occurs, the usage data accumulates correctly and the Since timestamp is preserved.
244-246: Test assertions for usage at reset timeVerifies that at the exact reset time, usage is zero and the Since timestamp is updated to match the reset time, enforcing the reset behavior.
openmeter/entitlement/metered/reset_test.go (2)
236-236: Updated to use service instead of repositoryThe code now uses the new balanceSnapshotService instead of the direct repository, aligning with the service wrapper approach introduced in this PR.
252-252: Updated retrieval to use serviceConsistently updated to use balanceSnapshotService for retrieving snapshots, maintaining the architectural change throughout the test file.
openmeter/billing/worker/subscription/sync_test.go (3)
21-21: Added new import for balance moduleThe addition of the credit/balance import is necessary for the new balance snapshot service functionality.
215-219: Balance snapshot service implementationGood implementation of the new balance snapshot service which replaces direct access to the repository. This service wrapper approach ensures all access to the repository goes through a single point, allowing for consistent handling of usage data.
223-235: Improved parameter organization using configuration structThe refactoring to use a configuration struct instead of individual parameters improves code maintainability and makes it easier to add new parameters in the future. The addition of the BalanceSnapshotService and SnapshotGracePeriod fields aligns with the PR objective of enhancing snapshot functionality.
openmeter/credit/adapter/balance_snapshot.go (6)
13-13: Added entutils import for transaction handlingThis import is necessary for the transaction management improvements in this file.
22-22: Return concrete type instead of interfaceThe function now returns a concrete type instead of an interface. This is consistent with the service wrapper approach being implemented.
28-35: Transaction handling for InvalidateAfter methodGood implementation of transaction handling using the entutils package. This ensures the database operations are executed within a transaction context, improving data consistency.
37-58: Transaction handling for GetLatestValidAt methodWell-structured implementation of transaction handling for fetching data. The method maintains its existing error handling and return types while adding transaction support.
60-77: Transaction handling and Usage field in Save methodThe Save method now uses transaction handling and sets the new Usage field in the balance snapshot entity. This is a key implementation aligned with the PR objective of incorporating usage information in snapshots.
79-89: Updated mapping function for Usage fieldThe mapping function now properly handles the new Usage field, ensuring it's correctly transferred from the database entity to the domain model when present.
openmeter/registry/builder/entitlement.go (4)
7-7: Added config package importThe new import is necessary for the EntitlementsConfiguration addition.
26-32: Added EntitlementsConfiguration to options structGood addition of configuration field to the options struct, enabling the configuration of entitlement-related settings such as grace period in a centralized way.
54-58: Created balance snapshot serviceThis change implements the service wrapper around the repository, which is a key part of the PR objectives. The service abstraction provides a good separation of concerns.
60-72: Refactored credit connector initializationThe change to use a configuration struct instead of individual parameters improves code maintainability and readability. The addition of the SnapshotGracePeriod from the configuration enables more flexibility in configuration.
openmeter/entitlement/metered/lateevents_test.go (5)
12-12: Added balance package importThis import is necessary for using the new balance snapshot service.
28-28: Added isodate package importThis import is required for parsing the ISO 8601 duration format used for the grace period.
144-149: Implemented balance snapshot service in testsThe test has been properly updated to use the new balance snapshot service instead of working directly with the repository. This ensures the test reflects the new architecture.
152-164: Updated credit connector initializationThe test now properly uses the new configuration struct approach for initializing the credit connector, including setting a grace period of one week. This ensures consistency with the production code.
190-190: Updated return value in test setupThe setupMockedConnector function now correctly returns the balance snapshot service instead of the repository, aligning with the changes in the production code.
openmeter/credit/connector.go (2)
21-22: Good use of struct embedding for clarity and maintainability.
By embeddingCreditConnectorConfig, theconnectortype inherits config fields directly, minimizing boilerplate. This promotes cleaner code and straightforward usage of config fields.
39-42: Constructor simplifies parameter passing.
Switching to a singleCreditConnectorConfigparameter is well-structured and reduces method signature bloat. Great improvement in readability.openmeter/credit/balance/usage.go (3)
1-20: Interface-based design and imports appear consistent.
TheUsageQuerierinterface and related imports set a clear contract for querying usage. Keeping it minimal but well-defined sets a good foundation for future extension.
39-123: Implementation ofQueryUsagecovers multiple aggregations thoroughly.
- Good usage of
alpacadecimalto preserve precision when subtracting unique counts.- Proper fallback to 0 usage when times match or no data is found.
- Carefully handles different aggregator types (
UniqueCount,Sum,Count).Potential considerations:
- Negative usage: If usage at “from” unexpectedly exceeds usage at “to,” you may end up with negative values. Clarify if this scenario is possible or needs special handling.
- Inexact float:
InexactFloat64()may cause rounding issues for large or high-precision usage values. Verify if slight floating-point deviations are acceptable.Overall, the logic is straightforward and robust for typical usage patterns.
Do you need a script to confirm that negative usage never occurs under normal system operations?
125-134: Carefully handling row count ingetValueFromRows.
Returning 0.0 for zero rows is logical for usage queries, and erroring out on multiple rows avoids ambiguous usage results. Ensure upstream queries can only yield at most one row under all aggregator scenarios.openmeter/credit/balance/service.go (5)
1-19: Interface definitions neatly capture snapshot operations.
Methods for invalidation, retrieval, and saving form a coherent API for managing snapshot lifecycle. The privateservice()method is a standard trick to prevent accidental direct struct implementations.
32-49: Custom UsageQuerier instantiation is well-structured.
Composing a specializedUsageQuerierinsideNewSnapshotServicedemonstrates good DI patterns. It localizes usage logic while leveraging the flexible config methods.
53-55: InvalidateAfter logic is straightforward.
Delegating directly to the repository is clean and easy to follow. No concerns here.
57-85: Late usage filling on retrieved snapshots might cause partial data if usage is already partially saved.
It’s correct to recalculate usage ifres.Usage.IsZero(), but be aware of edge cases if usage was only partially saved. Confirm that subsequent saves will update the usage to prevent data drift.If you’d like, I can generate a script to check for any partial usage patterns or confirm every snapshot eventually sets usage properly.
87-89: Simple pass-through ofSaveoperation to the repo.
The layering with a dedicatedRepokeeps this method small and specialized. Implementation is good.openmeter/credit/engine/run.go (4)
44-50: Well-implemented handling of usage information between periodsThis new code block correctly resets the snapshot usage information when starting a new period between resets. By initializing a new
SnapshottedUsagewith the correct period start time and zeroing out the usage, it ensures proper tracking of usage metrics across period boundaries.
85-85: Appropriately updated to pass usage information to history creationThe
NewGrantBurnDownHistoryfunction call was correctly updated to include the starting snapshot's usage information, ensuring usage metrics are properly incorporated into the history tracking.
215-215: Consistent implementation of usage data passing to history creationThis change is consistent with the pattern established earlier, passing the starting snapshot's usage information to the history creation function.
225-228: Comprehensive implementation of usage tracking in snapshotsThe snapshot return value now properly includes usage information with:
- The original measurement period start time preserved via
params.StartingSnapshot.Usage.Since- Cumulative usage calculation by adding previous usage to what was recorded in the current history
This ensures that usage data is accurately preserved across multiple calculations and snapshots.
openmeter/ent/db/migrate/schema.go (2)
207-208: Appropriate schema update for usage trackingThe addition of the
usagecolumn as a JSON field to theBalanceSnapshotsColumnsarray is a good implementation choice to support the newSnapshottedUsagestruct. Using a JSON type allows flexibility in the structure while maintaining the ability to query and index efficiently.
222-222: Correctly adjusted foreign key and index referencesThe foreign key reference and index definitions have been properly updated to reflect the new column position after adding the
usagecolumn. This prevents any schema inconsistencies that could lead to runtime errors.Also applies to: 236-236, 241-241, 246-246
openmeter/entitlement/metered/balance_test.go (4)
263-270: Well-implemented architectural change from repository to service patternThe code has been refactored to use
balanceSnapshotService.Saveinstead of direct repository access, which is a good architectural improvement for better separation of concerns. The test correctly initializes the newUsagefield structure with appropriate values.
283-295: Consistent service pattern implementation with proper assertionsThis section continues the repository-to-service refactoring pattern and correctly asserts the expected structure of the retrieved snapshot, including the new
Usagefield with its components.
305-320: Thorough validation of snapshot data including usage trackingThe test correctly validates both the retrieval mechanism and the content of the retrieved snapshot, with specific assertions for the
Usagefield'sSinceandUsageproperties. The test properly verifies that snapshots at reset times have zeroed usage values.
324-447: Well-designed test for usage tracking across periodsThis new test case thoroughly validates the functionality of recording and retrieving usage data across different periods. It:
- Sets up grants spanning multiple periods
- Registers usage events in different periods
- Creates breakpoints in history with new grants
- Verifies that snapshots correctly record usage from the right starting point
- Validates that the total usage calculation is accurate across resets and periods
This is a comprehensive test that ensures the usage tracking functionality works as expected in a variety of scenarios.
openmeter/entitlement/metered/utils_test.go (3)
31-31: Import usage looks good.
No concerns regarding the addition of theisodateimport.
131-141: Double-check SnapshotGracePeriod consistency.
You're using a 1-week grace period here (P1W). If your current requirement is for a 1-day grace period, please ensure alignment in tests and production code to avoid confusion.
163-163: Field assignment looks correct.
No issues with addingsnapshotServiceto the returned dependencies struct.test/entitlement/regression/framework_test.go (4)
31-31: New import usage looks fine.
No concerns about addingisodatehere.
123-128: Initialization ofbalanceSnapshotService.
The creation ofbalance.NewSnapshotServiceis correctly parameterized. Ensure appropriate test coverage for boundary scenarios.
131-142: Confirm grace period logic inCreditConnectorConfig.
You set theSnapshotGracePeriodtoisodate.NewPeriod(...)for 1 day. This is presumably aligned with updated requirements, but verify consistency with any references to a 1-week grace period.
184-184: Balanced injection into dependencies.
AddingBalanceSnapshotServiceto your dependencies struct is straightforward and consistent with other fields.openmeter/credit/balance.go (2)
25-26: New method signature for GetBalanceSinceSnapshot.
Defining a separate method for partial computations is a good addition. Keep an eye on consistent usage across the codebase.
110-128: Check the rounding logic inGetBalanceAt.
Truncating and then adding a minute may skip up to nearly a full minute of usage data. Verify that this behavior is intentional and aligned with the expected business rules.openmeter/credit/helper.go (13)
14-14: No concerns about the new import.
19-22: Public method rename looks good.
The expanded doc comment and new name reflect the intent to provide a valid snapshot or fallback to recalculating from the start. This makes the function more self-explanatory.
28-28: OwnerConnector usage.
Switching to the exportedOwnerConnectoraligns with the uppercase naming convention. No issues found.
33-33: Active grants retrieval is consistent.
The call toListActiveGrantsBetweenmatches the rest of the logic for snapshot backfill. Looks good.
88-111: UsageQuerier approach looks solid.
This design tightly scopes the queried owner to avoid cross-owner logic confusion. The inlined callback functions also make the usage flow more transparent. Good job.
121-122: Good direct delegation to usageQuerier.
No issues with querying usage in the provided time range as you’ve already validated bounds above.
138-139: Snapshot logic extraction is well-structured.
Separating outsnapshotEngineResultenhances readability and reuse. No concerns here.
153-153: Saving snapshot within the segment loop looks correct.
The error handling is straightforward; no issues found regarding concurrency or deadlocks.
164-167: Inactive grants removal logic is consistent.
This ensures snapshots persist only relevant grants. Consider confirming test coverage for scenarios with few or many inactive grants.
169-171: Single-snapshot save.
Saving via a slice parameter is fine if the implementation expects multiple snapshots. No red flags spotted.
173-173: Consistent logging.
Good use ofDebugContextfor structured logs. All fields appear relevant.
175-176: Clean final return.
No further improvements needed.
147-148:Details
✅ Verification successful
Double-check boundary condition.
Using!seg.From.After(snapParams.before)means segments starting exactly atsnapParams.beforewill still be persisted. Confirm that this inclusive check is intentional.
🏁 Script executed:
#!/bin/bash # Verify usage of inclusive boundary conditions across the code: rg --context 3 "After\("Length of output: 66017
Boundary Condition Verified: Inclusive Comparison is Intentional
After reviewing similar boundary checks across the codebase, it's clear that using
!seg.From.After(snapParams.before)to include segments that start exactly atsnapParams.beforeis consistent with our current design. This inclusive check aligns with comparable patterns (e.g., using!time.After(…)in several other modules) ensuring correct handling of edge cases such as backfilling, granting, and resetting.
- Location:
openmeter/credit/helper.go(Lines 147-148)- Summary: The code intentionally persists segments where
seg.Fromis equal tosnapParams.before, following the established convention elsewhere in the system.openmeter/credit/engine/history.go (6)
69-69: New parameter for usageAtStart is logical.
Providing the initial usage in the constructor centralizes the usage initialization. This clarifies baseline usage for the entire history.
89-89: Returning usageAtStart is consistent.
Storing both segments and usage in the returned struct sets the foundation for refined usage tracking logic.
93-95: Expanding the struct to include usageAtStart is clear.
These fields ensure the history can account for preexisting usage.
96-118: New GetSnapshotAtStartOfSegment method is well-defined.
Logic to compute usage resets and overage at segment boundaries is straightforward. Make sure tests exist for edge cases (e.g., segmentIndex = 0 and final segment).
120-155: Usage reset logic is properly encapsulated.
Methodically searching for the last reset ensures that usage accumulates correctly. Double-check coverage for consecutive resets.
161-161: Renamed method clarifies intent.
TotalUsageInHistoryis more descriptive and consistent with the rest of the usage-based naming.openmeter/ent/db/mutation.go (4)
4442-4489: Implementation is consistent with existing patternsThe implementation of the
usagefield management methods (Set, Get, Clear, etc.) follows the established patterns in the codebase. The error handling inOldUsageproperly checks for update operations and ID presence.
4713-4713: Capacity adjustment for the new fieldThe slice capacity has been increased from 9 to 10 to accommodate the new field. This is a good optimization to avoid unnecessary reallocations.
4732-4734: Fields method properly includes the usage fieldThe usage field is correctly added to the returned slice when it exists, consistent with how other fields are handled.
4764-4765: Field accessor methods are correctly implementedThe implementation of the
Field,OldField,SetField,ClearedFields,ClearField, andResetFieldmethods has been updated to handle the newusagefield consistently with the existing pattern.Also applies to: 4793-4794, 4852-4858, 4940-4942, 4960-4962, 4989-4991
| updated_at *time.Time | ||
| deleted_at *time.Time | ||
| grant_balances *balance.Map | ||
| usage **balance.SnapshottedUsage |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Double pointer usage seems unusual
The field usage is defined as **balance.SnapshottedUsage (double pointer). While this might be intentional for managing nil values, double pointers can make the code harder to reason about and increase the chance of nil-related bugs.
Consider whether a single pointer would be sufficient:
- usage **balance.SnapshottedUsage
+ usage *balance.SnapshottedUsageLet's verify the usage pattern:
🏁 Script executed:
#!/bin/bash
# Check how SnapshottedUsage is used elsewhere in the codebase
rg "balance.SnapshottedUsage" --type go -A 2 -B 2Length of output: 9109
Action Required: Simplify pointer usage in mutation field
After verifying how balance.SnapshottedUsage is used throughout the codebase, it’s clear that a double pointer is unnecessary. The field is declared as **balance.SnapshottedUsage only in the mutation file, while elsewhere (e.g., in schema and snapshot structures) a single pointer is used. In the mutation's setter, you currently take a pointer (bu) and then store its address (using &bu), which complicates the code and risks nil-related bugs.
Please update the code as follows:
- In
openmeter/ent/db/mutation.go:- Change the field declaration from:
- usage **balance.SnapshottedUsage + usage *balance.SnapshottedUsage
- Update the setter accordingly:
-func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) { - m.usage = &bu -} +func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) { + m.usage = bu +}
- Change the field declaration from:
This change simplifies the code by eliminating the unnecessary double pointer and aligns the usage pattern with the rest of the codebase.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| usage **balance.SnapshottedUsage | |
| // ... other parts of openmeter/ent/db/mutation.go ... | |
| // BalanceSnapshotMutation represents a mutation for a balance snapshot. | |
| type BalanceSnapshotMutation struct { | |
| // ... other fields ... | |
| - usage **balance.SnapshottedUsage | |
| + usage *balance.SnapshottedUsage | |
| // ... other fields ... | |
| } | |
| // SetUsage updates the usage field for the balance snapshot mutation. | |
| -func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) { | |
| - m.usage = &bu | |
| -} | |
| +func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) { | |
| + m.usage = bu | |
| +} | |
| // ... remaining parts of the file ... |
There was a problem hiding this comment.
@tothandras lets add a CodeRabbit exclusion rule for generated code, this is funny to see but not too helpful
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
| return errors.New("gracePeriod is required") | ||
| } | ||
|
|
||
| if _, err := c.GracePeriod.Parse(); err != nil { |
There was a problem hiding this comment.
Let's also validate that it's a positive value.
| } | ||
|
|
||
| if err := m.balanceSnapshotRepo.Save(ctx, params.owner, []balance.Snapshot{snap}); err != nil { | ||
| if _, err := m.saveSnapshot(ctx, snapParams, snap); err != nil { |
There was a problem hiding this comment.
We need to be careful regarding time truncation here. I think we are fine as grants and resets are truncated, but we must never store even with the new engine such a snapshot that is not truncated to an exact second.
|
|
||
| err = m.balanceSnapshotRepo.WithTx(ctx, tx).Save(ctx, ownerID, []balance.Snapshot{startingSnap}) | ||
| // Let's save the snapshot | ||
| snap, err = m.saveSnapshot(ctx, snapshotParams{ |
There was a problem hiding this comment.
docs: We should also document that a reset causes the late events coming with times before the reset time to be not included in the entitlement history e.g. in case of an overflow.
There was a problem hiding this comment.
That's not 100%. A late-event arriving before a reset will cause a historical inconsistency, i.e. if you were to "delete" the reset and do it again, it would yield a different result. This in practice means that programmatic and manual resets handle them differently. As late events are not properly addressed system-wise, I'd say this is out of scope for now.
| GetLatestValidAt(ctx context.Context, owner models.NamespacedID, at time.Time) (Snapshot, error) | ||
| Save(ctx context.Context, owner models.NamespacedID, balances []Snapshot) error | ||
| // To make sure repo doesn't implement the service interface | ||
| service() |
|
|
||
| func (m *connector) saveSnapshot(ctx context.Context, params snapshotParams, snap balance.Snapshot) (balance.Snapshot, error) { | ||
| // Let's validate the timestamp | ||
| if snap.At.Truncate(m.Granularity) != snap.At { |
turip
left a comment
There was a problem hiding this comment.
One comment otherwise looks good.
939f527 to
820a7ce
Compare
820a7ce to
13a75fc
Compare
Overview
Part II
Notes
Summary by CodeRabbit
New Features
Bug Fixes
Tests
GetLatestValidAtmethod of theSnapshotService, covering various scenarios for usage data handling.