Skip to content

refactor: subject fixes - #2957

Merged
turip merged 2 commits into
mainfrom
refactor/subject-fixes
Jun 7, 2025
Merged

turip merged 2 commits into
mainfrom
refactor/subject-fixes

Conversation

@turip

@turip turip commented Jun 6, 2025 •

Copy link
Copy Markdown
Member

Misc refactors to make the subjects codebase more aligned with our transaction handling pracices.

Summary by CodeRabbit

  • New Features

    • Introduced more robust subject management with improved transaction handling and input validation.
    • Added new methods for retrieving and deleting subjects by strongly typed identifiers.
    • Added centralized subject resolution function to handle not found and error cases gracefully.
  • Refactor

    • Unified and strengthened type usage for subject operations, replacing pointer returns with value types for consistency.
    • Updated method signatures and naming for clarity and stronger typing across subject-related interfaces and services.
    • Enhanced error handling and resource cleanup during subject adapter initialization.
    • Refactored adapter and service layers to use transactional contexts for subject operations.
    • Updated HTTP handlers to use namespaced identifiers and value types consistently.
  • Bug Fixes

    • Improved handling of nullable fields and error cases in subject update and retrieval operations.
  • Tests

    • Updated test service implementations to match new method signatures and parameter types.

@turip
turip requested a review from a team as a code owner June 6, 2025 12:33
@coderabbitai

coderabbitai Bot commented Jun 6, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change refactors the subject management subsystem to use value types instead of pointers for Subject entities, introduces strong typing for IDs and keys, and adds explicit transaction management to the adapter. Service and adapter interfaces are updated for consistency, with improved input validation and error handling. Related construction, handler, and worker code are updated accordingly.

Changes

Files/Groups Change Summary
app/common/subject.go Updated NewSubjectAdapter and NewSubjectService to return (subject.Adapter, error) and (subject.Service, error) respectively, reflecting constructors that return errors.
cmd/balance-worker/wire_gen.go
cmd/server/wire_gen.go
Updated initialization of subjectAdapter and subjectService to handle errors returned by their constructors, added cleanup calls on failure before returning errors.
openmeter/entitlement/balanceworker/entitlementhandler.go
openmeter/entitlement/balanceworker/recalculate.go
Replaced direct calls to GetByKeyWithFallback with calls to new resolveSubjectIfExists function for subject resolution, preserving existing error handling and logic.
openmeter/entitlement/balanceworker/subject.go Added new function resolveSubjectIfExists to centralize subject retrieval logic, returning a subject with only the key if not found, and wrapping other errors.
openmeter/server/server_test.go Updated NoopSubjectService methods to return value types instead of pointers for subjects, added Update method, changed parameter types to use strong typing for IDs and keys, and renamed DeleteById to Delete.
openmeter/subject/adapter.go Refactored Adapter interface: methods now return value types, renamed parameters for clarity, added GetByKey and GetById methods, renamed DeleteById to Delete, embedded entutils.TxCreator, and added GetSubjectAdapterInput struct with validation.
openmeter/subject/adapter/adapter.go Changed New constructor to return (subject.Adapter, error) and check for nil database client. Added transaction management methods Tx, WithTx, and Self. Renamed internal field for clarity. Adapter implements transaction user interface.
openmeter/subject/adapter/subject.go Refactored adapter methods to use pointer receivers, return value types, and execute within transactions. Added methods for retrieval and deletion by strongly typed IDs and keys. Improved handling of nullable fields and error cases. Updated pagination and filtering logic in List.
openmeter/subject/httphandler/subject.go Updated handler logic to use value types instead of pointers for subjects, changed deletion to use models.NamespacedID, and adjusted map and slice handling accordingly.
openmeter/subject/service.go Refactored Service interface: methods now return value types, use strong-typed IDs and keys, removed GetByKeyWithFallback, added explicit GetByKey and GetById methods, and renamed DeleteById to Delete.
openmeter/subject/service/service.go Updated service constructor to return error if adapter is nil. Refactored methods for input validation, transactional execution, and value return types. Removed GetByKeyWithFallback, added GetByKey and GetById, and renamed DeleteById to Delete.

Warning

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

🔧 golangci-lint (1.64.8)

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


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c27d6a0 and 5bd62f3.

📒 Files selected for processing (4)
  • app/common/subject.go (2 hunks)
  • cmd/balance-worker/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/subject/service/service.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • cmd/balance-worker/wire_gen.go
  • cmd/server/wire_gen.go
  • app/common/subject.go
  • openmeter/subject/service/service.go
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@turip turip added the release-note/ignore Ignore this change when generating release notes label Jun 6, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
openmeter/subject/adapter/subject.go (1)

62-72: Track the technical debt for nullable field handling.

The FIXME comment correctly identifies this as a unique pattern that should be refactored. Consider creating a helper function or adopting a consistent pattern across all adapters.

Would you like me to create an issue to track this technical debt and propose a solution for consistent nullable field handling across all adapters?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2e7936 and c27d6a0.

📒 Files selected for processing (13)
  • app/common/subject.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (2 hunks)
  • openmeter/entitlement/balanceworker/recalculate.go (1 hunks)
  • openmeter/entitlement/balanceworker/subject.go (1 hunks)
  • openmeter/server/server_test.go (1 hunks)
  • openmeter/subject/adapter.go (1 hunks)
  • openmeter/subject/adapter/adapter.go (1 hunks)
  • openmeter/subject/adapter/subject.go (2 hunks)
  • openmeter/subject/httphandler/subject.go (4 hunks)
  • openmeter/subject/service.go (1 hunks)
  • openmeter/subject/service/service.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
app/common/subject.go (1)
openmeter/subject/adapter.go (1)
  • Adapter (12-22)
cmd/balance-worker/wire_gen.go (1)
app/common/subject.go (1)
  • NewSubjectAdapter (54-58)
cmd/server/wire_gen.go (2)
app/common/subject.go (1)
  • NewSubjectAdapter (54-58)
cmd/server/wire.go (1)
  • Application (41-77)
openmeter/subject/adapter/adapter.go (5)
openmeter/ent/db/client.go (2)
  • Client (65-153)
  • Driver (258-262)
openmeter/subject/adapter.go (1)
  • Adapter (12-22)
pkg/framework/entutils/transaction.go (2)
  • TxUser (179-195)
  • TxDriver (76-88)
openmeter/ent/db/tx.go (1)
  • Tx (15-108)
openmeter/ent/db/expose.go (1)
  • NewTxClientFromRawConfig (78-176)
openmeter/server/server_test.go (5)
openmeter/subject/service.go (3)
  • CreateInput (41-47)
  • UpdateInput (68-74)
  • ListParams (33-38)
openmeter/ent/db/subject.go (2)
  • Subject (17-38)
  • Subject (41-56)
openmeter/subject/subject.go (1)
  • Subject (11-18)
openmeter/entitlement/balanceworker/worker.go (1)
  • NamespacedID (38-38)
pkg/models/key.go (1)
  • NamespacedKey (5-8)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (25)
openmeter/entitlement/balanceworker/entitlementhandler.go (2)

269-275: LGTM: Consistent refactoring to use centralized subject resolution.

The replacement of GetByKeyWithFallback with resolveSubjectIfExists aligns with the broader refactoring to use stronger typing and centralized subject resolution logic. The error handling is preserved correctly.


341-347: LGTM: Consistent pattern applied for deleted snapshot events.

The same refactoring pattern is correctly applied here, maintaining consistency across the codebase. The resolveSubjectIfExists helper function centralizes the subject resolution logic effectively.

openmeter/entitlement/balanceworker/recalculate.go (1)

328-334: LGTM: Refactoring applied consistently.

The replacement of GetByKeyWithFallback with resolveSubjectIfExists follows the same pattern used throughout the codebase refactoring. The error handling and return behavior are preserved correctly.

app/common/subject.go (1)

56-58: LGTM: Improved error handling for adapter initialization.

The function signature change to return (subject.Adapter, error) enables proper error handling during adapter creation. This aligns with Go best practices for initialization functions and allows upstream callers to handle initialization failures gracefully.

cmd/balance-worker/wire_gen.go (1)

238-247: LGTM: Proper error handling and resource cleanup.

The error handling for NewSubjectAdapter follows the established pattern in this wire-generated file. The cleanup sequence is correctly called in reverse order (cleanup6 through cleanup) to ensure proper resource management when adapter creation fails.

cmd/server/wire_gen.go (1)

461-471: LGTM! Proper error handling for subject adapter initialization.

The error handling and cleanup sequence is correctly implemented, following the established pattern in this generated file where resources are cleaned up in reverse order of initialization.

openmeter/entitlement/balanceworker/subject.go (1)

11-24: LGTM! Well-implemented subject resolution helper.

The function correctly handles the not-found case by returning a minimal subject with only the key populated, which aligns with the previous GetByKeyWithFallback behavior. Error wrapping provides good context for debugging.

openmeter/subject/httphandler/subject.go (2)

321-324: LGTM! Improved type safety with strongly typed deletion.

The change to use models.NamespacedID with explicit namespace and ID fields improves type safety and makes the API more explicit about what's being deleted.


98-98: LGTM! Consistent use of value types.

The changes from pointer to value types for Subject entities align with the broader refactoring and reduce the risk of nil pointer dereferences.

Also applies to: 188-189, 193-193, 196-196

openmeter/subject/adapter/adapter.go (3)

16-24: LGTM! Good defensive programming with nil check.

The constructor now properly validates the required database client parameter and returns a descriptive error, preventing runtime panics from nil pointer dereferences.


26-29: LGTM! Compile-time interface verification.

Good practice to verify interface implementations at compile time. This ensures the adapter correctly implements both the subject.Adapter and transaction user interfaces.


35-55: LGTM! Well-implemented transaction support.

The transaction methods are correctly implemented:

  • Tx properly hijacks the transaction and wraps it with error handling
  • WithTx creates a new adapter instance bound to the transaction
  • Self provides the identity function required by the TxUser interface

This enables proper transaction management for subject operations.

openmeter/subject/service.go (1)

12-22: LGTM: Excellent interface improvements for type safety and consistency.

The refactored service interface demonstrates strong improvements:

  • Value returns eliminate potential nil pointer issues
  • Strong typing with models.NamespacedKey and models.NamespacedID enhances type safety
  • Clear method separation (GetByKey vs GetById) improves API clarity
  • Appropriate deprecation guidance for the convenience method
openmeter/server/server_test.go (1)

1514-1540: LGTM: Test service correctly implements the refactored interface.

The NoopSubjectService has been properly updated to match the new service interface:

  • Return types correctly changed to subject.Subject values
  • Method signatures align with the refactored interface including typed parameters
  • Maintains appropriate no-op behavior for testing
openmeter/subject/service/service.go (4)

27-35: LGTM: Excellent implementation of input validation and transaction management.

The Create method demonstrates best practices:

  • Input validation with proper error wrapping using models.NewGenericValidationError
  • Transaction management with transaction.Run aligns with PR objectives
  • Value return type improves consistency

38-46: LGTM: Consistent implementation pattern.

The Update method follows the same excellent pattern as Create with validation and transaction management.


56-75: LGTM: Strong typing with proper validation.

The new GetById and GetByKey methods demonstrate excellent practices:

  • Strong typing with models.NamespacedID and models.NamespacedKey
  • Input validation for typed parameters
  • Consistent transaction wrapping
  • Clear method separation improves API usability

85-93: LGTM: Proper transaction handling for delete operations.

The Delete method (renamed from DeleteById) correctly:

  • Uses strong typing with models.NamespacedID
  • Includes input validation
  • Uses transaction.RunWithNoValue appropriate for operations without return values
openmeter/subject/adapter.go (2)

12-22: LGTM: Adapter interface properly aligned with service changes.

The adapter interface demonstrates excellent improvements:

  • Value returns consistent with service interface
  • Strong typing with models.NamespacedKey and models.NamespacedID
  • Transaction support through entutils.TxCreator embedding
  • Clear method separation and consistent naming

24-40: LGTM: Well-designed input validation struct.

The GetSubjectAdapterInput struct with validation logic shows good design:

  • Clear validation requirements (namespace required, ID or Key required)
  • Proper error messages for validation failures
  • Follows consistent validation patterns
openmeter/subject/adapter/subject.go (5)

20-49: Well-implemented transactional Create method with proper error handling.

The refactoring to use value types and transaction management improves consistency. The constraint error handling for duplicate keys provides clear feedback.


106-160: Excellent implementation of flexible subject retrieval with deterministic behavior.

The function properly handles the ambiguity of ID vs key lookups by preferring ID matches over key matches. This deterministic behavior ensures consistent results.


162-184: Clean implementation with strong typing.

Good use of models.NamespacedKey for type safety and validation.


211-263: Comprehensive list implementation with advanced features.

The pagination, filtering, searching, and sorting capabilities are well-implemented. The null handling in display name sorting ensures consistent ordering.


289-291: Good defensive programming for metadata initialization.

Ensuring metadata is never nil prevents potential nil pointer issues downstream.

@turip
turip enabled auto-merge (squash) June 7, 2025 04:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants