-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
feat: add kling update balance #2409
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
feat: add kling update balance #2409
Conversation
WalkthroughAdds a pluggable balance update hook: defines a BalanceUpdater interface and makes updateChannelBalance delegate to a task adaptor implementing it. Implements UpdateBalance for the Kling task adaptor, which queries Kling's costs endpoint, parses response, computes remaining balance, and updates the channel. Changes
Sequence DiagramsequenceDiagram
participant Controller as Controller\n(updateChannelBalance)
participant Relay as Relay\n(task adaptor lookup)
participant Adaptor as Kling TaskAdaptor\n(UpdateBalance)
participant API as Kling API
participant DB as Channel Storage
Controller->>Relay: Request task adaptor for channel.platform
Relay-->>Controller: TaskAdaptor instance
alt Adaptor implements BalanceUpdater
Controller->>Adaptor: UpdateBalance(channel)
Adaptor->>Adaptor: Determine base URL & time window (1y)
Adaptor->>Adaptor: Build costs query URL
Adaptor->>Adaptor: Generate JWT from channel key
Adaptor->>API: GET /costs with Authorization: Bearer <JWT>
API-->>Adaptor: HTTP response (JSON)
Adaptor->>Adaptor: Validate codes, parse items
Adaptor->>Adaptor: Sum remaining quantities (online packs)
Adaptor->>DB: Persist updated channel balance
Adaptor-->>Controller: return (float64, error)
else Adaptor does not implement BalanceUpdater
Controller->>Controller: Compute balance via base-URL fallback
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
controller/channel-billing.go (1)
15-15: Adaptor-basedBalanceUpdaterhook is a clean extension point; consider interface placementThe new
BalanceUpdaterinterface plus therelay.GetTaskAdaptorhook inupdateChannelBalanceis a solid way to delegate provider‑specific balance logic (e.g., Kling) without further bloating this controller. For adaptors that don’t implementBalanceUpdater, the old behavior is preserved via the existingswitchonchannel.Type, which is exactly what we want.One optional design tweak: since this interface conceptually belongs to the relay/adaptor layer, you might consider moving
BalanceUpdaterto therelayorrelay/channelpackage and having controllers depend only on that interface type. That would keep controller more declarative and reduce knowledge of adaptor details here.Also applies to: 360-369
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
controller/channel-billing.go(2 hunks)relay/channel/task/kling/adaptor.go(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
Applied to files:
relay/channel/task/kling/adaptor.go
🧬 Code graph analysis (2)
controller/channel-billing.go (2)
relay/relay_adaptor.go (1)
GetTaskAdaptor(132-162)constant/task.go (1)
TaskPlatform(3-3)
relay/channel/task/kling/adaptor.go (3)
model/channel.go (1)
Channel(21-58)constant/channel.go (1)
ChannelBaseURLs(61-119)service/http_client.go (1)
NewProxyHttpClient(82-156)
🔇 Additional comments (1)
relay/channel/task/kling/adaptor.go (1)
408-465: Kling balance computation flow looks sound; confirm API semantics (window & units)The
UpdateBalanceimplementation is cohesive: it derivesbaseURLwith a sane fallback, queries a 1‑year/account/costswindow, filtersstatus == "online"packs, sumsremaining_quantity, and updates the channel viachannel.UpdateBalance(balance). From a code perspective this is consistent with the rest of the controller’s balance updaters.The only thing to double‑check is the Kling API contract:
- That
start_time/end_timein milliseconds and a 1‑year window match the API’s expectations.- That
remaining_quantityis indeed the unit you want to treat as “balance” (and that summing only"online"packs is sufficient).If those assumptions hold, the implementation looks good.
Ensure response body is closed after reading.
There was a problem hiding this comment.
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)
relay/channel/task/kling/adaptor.go (1)
467-497: Resource leak fixed; optional cleanup remains.The
deferon line 483 correctly addresses the previous review concern about leakingres.Bodyon early returns. The explicit close on lines 493-495 is now redundant—the deferred close will execute after the return, attempting to close an already-closed body (harmless but unnecessary).To fully align with the past review and eliminate redundancy, apply this diff:
body, err := io.ReadAll(res.Body) if err != nil { return nil, err } - if err = res.Body.Close(); err != nil { - return nil, err - } return body, nil
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
relay/channel/task/kling/adaptor.go(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
Applied to files:
relay/channel/task/kling/adaptor.go
🔇 Additional comments (2)
relay/channel/task/kling/adaptor.go (2)
408-421: LGTM!The response structure is well-defined for parsing Kling cost query responses. The nested pointer for
Dataenables proper nil checking downstream.
423-465: LGTM!The balance update logic is well-structured with proper error handling at each step. The case-insensitive status comparison on line 459 provides robustness against API response variations, and the dual validation of both top-level and nested response codes ensures correctness.
增加可灵余额查询功能
Summary by CodeRabbit
New Features
Refactor
✏️ Tip: You can customize this high-level summary in your review settings.