Skip to content

Cscitech#16

Merged
CSCITech merged 3 commits into
mainfrom
cscitech
Jul 10, 2026
Merged

Cscitech#16
CSCITech merged 3 commits into
mainfrom
cscitech

Conversation

@CSCITech

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6e44b1c3-d348-4798-82e0-ddca0ee29721

📥 Commits

Reviewing files that changed from the base of the PR and between 57b4e1b and d57c0ce.

📒 Files selected for processing (2)
  • model/main.go
  • model/main_migration_test.go
📜 Recent review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: Backend checks
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.go: In Go business code, all JSON marshal/unmarshal operations must use the wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType) and must not directly call encoding/json for actual encode/decode work.
All database code must be compatible with SQLite, MySQL 5.7.8+, and PostgreSQL 9.6+; prefer GORM abstractions over raw SQL, avoid direct AUTO_INCREMENT/SERIAL, use commonGroupCol/commonKeyCol and commonTrueVal/commonFalseVal for DB-specific SQL, branch with common.UsingPostgreSQL/common.UsingSQLite/common.UsingMySQL, avoid unsupported DB-specific functions/operators without fallback, and make migrations work across all three databases.
When implementing a new relay channel, confirm whether the provider supports StreamOptions; if it does, add that channel to streamSupportedChannels.
For request structs parsed from client JSON and re-marshaled to upstream providers, optional scalar fields must use pointer types with omitempty so explicit zero/false values are preserved instead of dropped.
When working on tiered/dynamic billing expression code, read pkg/billingexpr/expr.md first and follow its documented expression language, architecture, token normalization, quota conversion, and versioning patterns.

**/*.go: All JSON marshal/unmarshal operations in Go business code must use the wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType) instead of directly importing or calling encoding/json for actual marshal/unmarshal work.
All database code in Go must remain compatible with SQLite, MySQL >= 5.7.8, and PostgreSQL >= 9.6; prefer GORM abstractions, avoid raw SQL unless necessary, use the shared DB helper variables for reserved words and boolean literals, branch with the common.UsingPostgreSQL / common.UsingSQLite / common.UsingMySQL flags when need...

Files:

  • model/main_migration_test.go
  • model/main.go
🔇 Additional comments (4)
model/main.go (3)

687-744: Past cross-DB inconsistency resolved. Both the PostgreSQL and MySQL branches now backfill NULLs and enforce bigint NOT NULL DEFAULT 0, and SQLite is skipped (dynamic typing already stores int64), so schema guarantees are consistent across all three supported databases.


746-758: LGTM!


700-726: 🩺 Stability & Availability

No action needed

model/main_migration_test.go (1)

8-28: LGTM!


📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Extended quota handling to use larger integer precision for user, affiliate, token, and billing-related workflows.
    • Added support helpers for reading quota values from request context as 64-bit integers.
  • Bug Fixes

    • Fixed quota sufficiency/availability checks and comparisons to use consistent 64-bit arithmetic across relay, billing, and pre-consumption flows.
    • Improved startup database migrations to correctly treat nullable/zero defaults by backfilling and enforcing NOT NULL DEFAULT 0 when needed.
  • Tests

    • Expanded quota boundary coverage and added a case rejecting quota values above the signed 64-bit maximum.

Walkthrough

Quota handling is migrated from int to int64 across user models, cache and database access, batch updates, controllers, logging, relay and billing arithmetic. Validation tests add int64 boundary and overflow coverage.

Changes

Quota Migration

Layer / File(s) Summary
Quota storage and persistence
model/user.go, model/user_cache.go, model/main.go
User quota fields, cache accessors, database reads, initialization, and column migration checks use int64-compatible values.
Quota mutation and batch updates
model/user.go, model/utils.go, model/channel.go, model/token.go
Quota mutation helpers and batch-update accumulators normalize quota deltas to int64.
Quota API and context interfaces
common/gin.go, controller/*.go, logger/logger.go, relay/common/relay_info.go
Context accessors, request fields, billing values, logging helpers, and relay quota fields support int64 values.
Quota checks and billing arithmetic
model/subscription.go, relay/mjproxy_handler.go, service/*.go
Quota comparisons and billing calculations explicitly use int64 operands.
Quota migration validation
controller/user_setting_test.go, model/*_test.go, service/*_test.go
Tests update numeric comparisons for int64 and cover quota boundaries, additions, and values beyond the int64 range.

Estimated code review effort: 4 (Complex) | ~45 minutes

Poem

A rabbit counts coins in a moonlit array,
“int64 keeps the big numbers at bay!”
Cache, relay, and billing align,
Batch updates hop in a widening line.
Tests guard the bounds with a thump and a cheer—
More quota can safely burrow here!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.21% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is too vague to indicate the actual change; it does not describe the code changes in this PR. Use a concise title that names the main change, such as the primary feature, fix, or refactor.
Description check ❓ Inconclusive The description is a PR template/instructions, not a meaningful summary of the code changes. Replace the template with a short human-written summary of what changed, why, and any validation performed.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cscitech

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@model/main.go`:
- Around line 700-717: Make the PostgreSQL migration consistent with the MySQL
path in the database schema update logic: before enforcing constraints, backfill
existing NULL values to 0, then set the column type to bigint, NOT NULL, and
DEFAULT 0 using PostgreSQL-compatible ALTER COLUMN clauses. Update the
PostgreSQL branch alongside the existing metadata handling and ensure the SQL
remains compatible with SQLite, MySQL, and PostgreSQL migration paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 32fcd447-e4b8-48d4-986e-81f4ef80a953

📥 Commits

Reviewing files that changed from the base of the PR and between e5dca9e and 57b4e1b.

📒 Files selected for processing (21)
  • common/gin.go
  • controller/billing.go
  • controller/user.go
  • controller/user_setting_test.go
  • logger/logger.go
  • model/channel.go
  • model/main.go
  • model/payment_method_guard_test.go
  • model/subscription.go
  • model/token.go
  • model/user.go
  • model/user_cache.go
  • model/user_update_test.go
  • model/utils.go
  • relay/common/relay_info.go
  • relay/mjproxy_handler.go
  • service/billing_session.go
  • service/pre_consume_quota.go
  • service/quota.go
  • service/task_billing_test.go
  • service/text_quota_test.go
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: Backend checks
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.go: In Go business code, all JSON marshal/unmarshal operations must use the wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType) and must not directly call encoding/json for actual encode/decode work.
All database code must be compatible with SQLite, MySQL 5.7.8+, and PostgreSQL 9.6+; prefer GORM abstractions over raw SQL, avoid direct AUTO_INCREMENT/SERIAL, use commonGroupCol/commonKeyCol and commonTrueVal/commonFalseVal for DB-specific SQL, branch with common.UsingPostgreSQL/common.UsingSQLite/common.UsingMySQL, avoid unsupported DB-specific functions/operators without fallback, and make migrations work across all three databases.
When implementing a new relay channel, confirm whether the provider supports StreamOptions; if it does, add that channel to streamSupportedChannels.
For request structs parsed from client JSON and re-marshaled to upstream providers, optional scalar fields must use pointer types with omitempty so explicit zero/false values are preserved instead of dropped.
When working on tiered/dynamic billing expression code, read pkg/billingexpr/expr.md first and follow its documented expression language, architecture, token normalization, quota conversion, and versioning patterns.

**/*.go: All JSON marshal/unmarshal operations in Go business code must use the wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType) instead of directly importing or calling encoding/json for actual marshal/unmarshal work.
All database code in Go must remain compatible with SQLite, MySQL >= 5.7.8, and PostgreSQL >= 9.6; prefer GORM abstractions, avoid raw SQL unless necessary, use the shared DB helper variables for reserved words and boolean literals, branch with the common.UsingPostgreSQL / common.UsingSQLite / common.UsingMySQL flags when need...

Files:

  • controller/billing.go
  • model/channel.go
  • service/pre_consume_quota.go
  • service/text_quota_test.go
  • relay/common/relay_info.go
  • common/gin.go
  • service/billing_session.go
  • service/quota.go
  • model/token.go
  • model/user_update_test.go
  • logger/logger.go
  • controller/user_setting_test.go
  • model/utils.go
  • relay/mjproxy_handler.go
  • model/subscription.go
  • model/user_cache.go
  • model/main.go
  • model/payment_method_guard_test.go
  • controller/user.go
  • service/task_billing_test.go
  • model/user.go
🔇 Additional comments (34)
model/payment_method_guard_test.go (1)

14-23: LGTM!

Also applies to: 92-97, 111-112, 215-217, 238-240, 285-286, 312-313, 340-341

model/user_update_test.go (1)

193-194: LGTM!

Also applies to: 228-229, 306-307, 343-344

service/task_billing_test.go (2)

86-90: LGTM!

Also applies to: 157-162


227-244: 🎯 Functional Correctness

Double-check the token/channel quota assertions

If Token.RemainQuota, Token.UsedQuota, or Log.Quota were widened to int64, the plain assert.Equal checks here will fail on type mismatch. Either switch these to assert.EqualValues or keep the field types consistent.

service/text_quota_test.go (1)

175-175: LGTM!

Also applies to: 228-228

controller/user_setting_test.go (2)

219-239: 🎯 Functional Correctness

Confirm isValidQuotaAddition(0, 0) is intended.
require.False(t, isValidQuotaAddition(0, 0)) makes zero-quota additions invalid; if the helper is meant to allow no-op additions, this assertion looks wrong.


241-253: 🎯 Functional Correctness

Confirm the test exercises the overflow path. TestManageUserRejectsQuotaValueAboveInt64Max only checks "success":false; without seeding id=1, the same result could come from a missing-user branch. Add a fixture or assert the specific error so the test can’t pass for the wrong reason.

model/user.go (3)

67-74: LGTM!

Also applies to: 581-590, 695-695, 752-752, 1339-1369, 1525-1532, 1552-1567


1442-1498: Confirm the module targets Go 1.18+
model/user.go:1442-1498 uses type-parameter constraints (~int | ~int64), which require Go 1.18 or newer. If the repo still supports an older toolchain, this won’t build.


592-633: 🎯 Functional Correctness

Check all TransferAffQuotaToQuota call sites against the new int64 signature. Any typed int argument needs an explicit cast.

model/user_cache.go (1)

18-25: LGTM!

Also applies to: 187-192, 231-234

model/main.go (1)

4-4: LGTM!

Also applies to: 670-673

model/utils.go (2)

23-30: LGTM!

Also applies to: 42-50, 70-77, 95-113


78-93: Confirm the int64→int cast boundary
Accumulated int64 deltas are still narrowed back to int for token/channel updates; confirm that quota handling is intentionally capped here and that these fields do not need the same int64 widening as the rest of the billing path.

model/channel.go (1)

855-861: LGTM!

model/token.go (1)

403-420: LGTM!

Also applies to: 433-450

service/pre_consume_quota.go (1)

41-48: LGTM!

Also applies to: 75-75

service/quota.go (1)

141-141: LGTM!

Also applies to: 480-480

common/gin.go (1)

173-188: LGTM!

controller/user.go (3)

410-412: LGTM!


1010-1174: LGTM!


991-1007: 🎯 Functional Correctness

Ensure maxUserQuotaValue matches the new int64 quota checks. If that constant is still an int or an untyped value outside int64 range, these comparisons can break on 32-bit builds or fail to compile.

logger/logger.go (1)

122-177: LGTM!

relay/common/relay_info.go (3)

120-120: LGTM!


474-474: LGTM!


124-124: 🗄️ Data Integrity & Integration

Check whether FinalPreConsumedQuota also needs the int64 widening

FinalPreConsumedQuota is still int while related quota fields were widened to int64.

model/subscription.go (1)

792-792: LGTM!

relay/mjproxy_handler.go (2)

213-213: LGTM!


520-520: LGTM!

service/billing_session.go (3)

308-308: LGTM!


364-364: LGTM!


345-345: 🗄️ Data Integrity & Integration

preConsumedQuota should likely be int64. It’s still declared as int, while the surrounding quota fields use int64, so large quota values can be narrowed before they reach this logic.

controller/billing.go (2)

12-27: 🩺 Stability & Availability

Check token before reading its fields. If model.GetTokenById can return a nil token on error, the token.ExpiredTime / quota reads will panic before err is handled.


72-82: 🩺 Stability & Availability

Potential nil dereference here token.UsedQuota is read before checking the GetTokenById error, so a failed lookup can panic on token being nil.

Comment thread model/main.go
@CSCITech
CSCITech merged commit 23e8d2d into main Jul 10, 2026
3 checks passed
This was referenced Jul 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant