Skip to content

Conversation

@feitianbubu
Copy link
Contributor

@feitianbubu feitianbubu commented Dec 11, 2025

增加可灵余额查询功能

Summary by CodeRabbit

  • New Features

    • Added platform-specific balance retrieval support with a Kling adaptor that queries remote cost data and updates channel balances automatically.
    • Introduced robust HTTP request handling for fetching balance/cost responses.
  • Refactor

    • Enhanced channel balance update flow to allow adaptors to short-circuit base calculation and supply balances directly.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 11, 2025

Walkthrough

Adds 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

Cohort / File(s) Summary
Controller integration
controller/channel-billing.go
Adds BalanceUpdater interface with UpdateBalance(channel *model.Channel) (float64, error) and updates updateChannelBalance to check for a task adaptor implementing this interface, delegating balance retrieval before falling back to previous base-URL logic.
Kling adaptor and HTTP helper
relay/channel/task/kling/adaptor.go
Adds klingCostsResponse type, (*TaskAdaptor) UpdateBalance(channel *model.Channel) (float64, error), and getResponseBody(method, url string, channel *model.Channel, headers http.Header) ([]byte, error). Build costs query (one-year window), create JWT from channel key, call Kling costs API via proxy-enabled client, validate/parse response, sum remaining quantities for online packs, update and return balance.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review JWT generation and header usage in UpdateBalance.
  • Validate parsing and error handling of the Kling response (codes, nested data).
  • Inspect getResponseBody for correct proxy client use, status checks, and body closing.
  • Confirm adaptor lookup and interface type assertion and fallback behavior in controller.

Poem

🐰 I hopped to the API, nose in the breeze,
JWT tucked tight, counting packs with ease,
Costs danced in rows, I summed what remained,
Balance now labeled, no hops unexplained,
A rabbit's small cheer for code freshly trained.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add kling update balance' directly and clearly describes the main change: implementing balance update functionality for the Kling platform integrations.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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: 1

🧹 Nitpick comments (1)
controller/channel-billing.go (1)

15-15: Adaptor-based BalanceUpdater hook is a clean extension point; consider interface placement

The new BalanceUpdater interface plus the relay.GetTaskAdaptor hook in updateChannelBalance is a solid way to delegate provider‑specific balance logic (e.g., Kling) without further bloating this controller. For adaptors that don’t implement BalanceUpdater, the old behavior is preserved via the existing switch on channel.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 BalanceUpdater to the relay or relay/channel package 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

📥 Commits

Reviewing files that changed from the base of the PR and between fca015c and 3d670bf.

📒 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 UpdateBalance implementation is cohesive: it derives baseURL with a sane fallback, queries a 1‑year /account/costs window, filters status == "online" packs, sums remaining_quantity, and updates the channel via channel.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_time in milliseconds and a 1‑year window match the API’s expectations.
  • That remaining_quantity is 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.
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: 0

🧹 Nitpick comments (1)
relay/channel/task/kling/adaptor.go (1)

467-497: Resource leak fixed; optional cleanup remains.

The defer on line 483 correctly addresses the previous review concern about leaking res.Body on 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d670bf and 99dbddd.

📒 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 Data enables 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.

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.

2 participants