Skip to content

Conversation

GAlexIHU
Copy link
Contributor

@GAlexIHU GAlexIHU commented Sep 26, 2025

Overview

Fixes #(issue)

Notes for reviewer

Summary by CodeRabbit

  • Bug Fixes
    • Creating credit grants now validates input: amount must be greater than zero and an effective-at timestamp is required.
    • Invalid requests receive clear, field-specific validation messages, preventing grant creation from proceeding with incorrect data.
    • Users get earlier feedback on submission issues, improving reliability and reducing failed transactions.

@GAlexIHU GAlexIHU requested a review from a team as a code owner September 26, 2025 13:19
@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Sep 26, 2025
@GAlexIHU GAlexIHU enabled auto-merge (squash) September 26, 2025 13:19
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

📝 Walkthrough

Walkthrough

Introduces validation errors and implements input validation for credit grants. Adds new error codes and validation issue variables for amount positivity and required effective-at timestamp. Integrates a Validate method into CreateGrantInput and invokes it in CreateGrant to fail early on invalid input.

Changes

Cohort / File(s) Summary
Credit validation errors
openmeter/credit/errors.go
Added two error codes and corresponding validation issues using models.NewValidationIssue: amount must be positive; effective_at must be set. Exposed as package-level variables.
Grant validation logic
openmeter/credit/grant.go
Added CreateGrantInput.Validate() enforcing Amount > 0 and EffectiveAt presence; CreateGrant now calls Validate and returns early on error.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately describes the primary change by indicating that validations have been added to grant input, directly reflecting the new validation logic introduced in the code.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch galexi/fix/grant-validations

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
openmeter/credit/grant.go (1)

36-44: Validation is good; consider finite-number check and consistent field keys.

  • Add a guard for NaN/Inf (NaN currently passes the >0 check due to comparison semantics).
  • Align attribute key with API field casing (“effectiveAt” vs “effective_at”) for consistency with JSON/SDKs.

Apply this diff to extend validation and align the attribute key:

 func (i CreateGrantInput) Validate() error {
-	if i.Amount <= 0 {
-		return ErrGrantAmountMustBePositive.WithAttr("amount", i.Amount)
-	}
-	if i.EffectiveAt.IsZero() {
-		return ErrGrantEffectiveAtMustBeSet.WithAttr("effective_at", i.EffectiveAt)
-	}
+	if i.Amount <= 0 {
+		return ErrGrantAmountMustBePositive.WithAttr("amount", i.Amount)
+	}
+	// Reject non-finite values
+	if math.IsNaN(i.Amount) || math.IsInf(i.Amount, 0) {
+		return models.NewGenericValidationError(fmt.Errorf("amount must be a finite number"))
+	}
+	if i.EffectiveAt.IsZero() {
+		return ErrGrantEffectiveAtMustBeSet.WithAttr("effectiveAt", i.EffectiveAt)
+	}
 	return nil
 }

Additionally add the import:

import "math"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a759fc and eaae331.

📒 Files selected for processing (2)
  • openmeter/credit/errors.go (1 hunks)
  • openmeter/credit/grant.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
openmeter/credit/grant.go (3)
openmeter/credit/errors.go (2)
  • ErrGrantAmountMustBePositive (7-12)
  • ErrGrantEffectiveAtMustBeSet (16-21)
openmeter/credit/grant/grant.go (1)
  • Grant (14-58)
openmeter/ent/schema/grant.go (5)
  • Grant (15-17)
  • Grant (19-26)
  • Grant (28-59)
  • Grant (61-66)
  • Grant (68-77)
openmeter/credit/errors.go (2)
pkg/models/errors.go (1)
  • ErrorCode (294-294)
pkg/models/validationissue.go (3)
  • NewValidationIssue (219-230)
  • WithFieldString (196-202)
  • WithWarningSeverity (214-216)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Code Generators
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
openmeter/credit/grant.go (1)

50-52: Early fail on invalid input looks right.
Keep this short‑circuit to avoid unnecessary DB work; ensure these validation errors map to a 4xx at the API boundary with structured issues.

Can you confirm the HTTP mapping and response shape for these validation issues (status code, body schema)?

openmeter/credit/errors.go (1)

5-21: Ensure With methods on ValidationIssue return a new copy*
Verify that all option methods (WithFieldString, WithWarningSeverity, etc.) use value receivers and don’t mutate the original ValidationIssue; if they mutate in place, package-level vars (ErrGrantAmountMustBePositive, ErrGrantEffectiveAtMustBeSet) will share state and race.

Comment on lines +7 to +12
var ErrGrantAmountMustBePositive = models.NewValidationIssue(
ErrCodeGrantAmountMustBePositive,
"amount must be positive",
models.WithFieldString("amount"),
models.WithWarningSeverity(),
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Severity mismatch: returning “warning” issues to fail the request.
You’re using WithWarningSeverity yet Validate() returns these as errors that block creation. Align severity with behavior.

Option A (preferred if available): switch to error severity.

 var ErrGrantAmountMustBePositive = models.NewValidationIssue(
 	ErrCodeGrantAmountMustBePositive,
 	"amount must be positive",
 	models.WithFieldString("amount"),
-	models.WithWarningSeverity(),
+	models.WithErrorSeverity(),
 )
 
 var ErrGrantEffectiveAtMustBeSet = models.NewValidationIssue(
 	ErrCodeEffectiveAtMustBeSet,
 	"effective at must be set",
-	models.WithFieldString("effective_at"),
-	models.WithWarningSeverity(),
+	models.WithFieldString("effectiveAt"),
+	models.WithErrorSeverity(),
 )

Option B (if no WithErrorSeverity exists): drop the explicit warning so it uses the default error severity.

-	models.WithWarningSeverity(),
+	// default to error severity

Also applies to: 16-21

🤖 Prompt for AI Agents
In openmeter/credit/errors.go around lines 7-12 (and similarly for lines 16-21),
the validation issues are created with WithWarningSeverity but Validate() treats
them as blocking errors; change the severity to an error by replacing
WithWarningSeverity() with WithErrorSeverity(), or if WithErrorSeverity() is not
available, remove the explicit WithWarningSeverity() call so the default (error)
severity is used, ensuring the declaration matches the runtime behavior.

Comment on lines +16 to +21
var ErrGrantEffectiveAtMustBeSet = models.NewValidationIssue(
ErrCodeEffectiveAtMustBeSet,
"effective at must be set",
models.WithFieldString("effective_at"),
models.WithWarningSeverity(),
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Field selector casing likely mismatched with API (“effective_at” vs “effectiveAt”).
Use the JSON field to help clients pinpoint issues.

Apply this diff if you keep Option A above:

-	models.WithFieldString("effective_at"),
+	models.WithFieldString("effectiveAt"),
🤖 Prompt for AI Agents
In openmeter/credit/errors.go around lines 16 to 21, the field selector uses
snake_case "effective_at" which likely mismatches the API JSON field; update the
validation issue to use the JSON field name "effectiveAt" (e.g., change
models.WithFieldString("effective_at") to models.WithFieldString("effectiveAt"))
so clients receive the correct field path for errors; keep the rest of the error
construction and warning severity unchanged.

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

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant