From 609ad396a649405801512bf1934472f26bbe3669 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com>
Date: Thu, 5 Nov 2026 12:02:33 +0800
Subject: [PATCH] =?UTF-8?q?feat(=E7=94=A8=E6=88=B7=E5=AF=86=E9=92=A5):=20?=
=?UTF-8?q?=E9=BE=99=E6=8A=AC=E5=A4=B4=E4=BD=99=E9=A2=9D=E6=8C=89=E4=BA=BA?=
=?UTF-8?q?=E6=B0=91=E5=B8=81=E5=8F=A3=E5=BE=84=E4=B8=8A=E7=95=8C=E9=9D=A2?=
=?UTF-8?q?=E2=80=94=E2=80=94credits=20=E6=9F=A5=E8=AF=A2=EF=BC=8B?=
=?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AB=AF/=E5=90=8E=E7=AE=A1=E4=B8=A4?=
=?UTF-8?q?=E4=B8=AA=E8=AF=BB=E5=8F=96=E9=9D=A2?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
上游事实(官方文档+2026-11-05 从主机B 直打实测):`GET /v1/skills/balance` 顶层 balance 是美元串("$12.345678"),
站内 ⚡=人民币口径在 credits 块(⚡ = 美元 × credits.per_usd)。要跟网页/账单对上必须取 credits,Java 里
不得出现任何汇率字面量。四条硬规则落在 LongtaitouBalanceClient:① 只认 credits.balance/available/frozen,
且 credits.unit 必须为 CREDIT、per_usd>0;② 顶层 $… 与 currency:USD 只作交叉校验(偏差 >0.5% 打 WARN),永不进展示;
③ credits 缺失/不可解析时不回落美元——把 12.34 当 ¥12.34 显示就是"美元当人民币"的假绿;④ 错误体
{error:{code,message,type}} 与 4xx/5xx 一律 available=false + message 原样透出,绝不抛、也不显示成 ¥0。
URL 由 LlmChannel.LONGTAITOU.host() 派生(配置键留空即用域名唯一正本),响应体限读 1MB。
不复用 UserApiSecretBalanceVo:那个类的 surplus/scope/low 语义全是 jikip 代理的,LLM 塞进去会让注释撒谎并
诱导下一个人在 useProxyBalance 里加分支(铁律 25「口径不得借」)。新建 UserLlmBalanceVo + 平行新建
UserLlmBalanceService(不扩 UserProxyBalanceService),缓存键 (userId,moduleKey) 5 分钟;渠道分档:t8star 不打
上游、available=false +「不提供余额查询」(贞贞有没有余额接口在册无判据,不许猜端点、更不许借龙抬头的数)。
后管走实时查、不落库(本窗零 Schema、零迁移):POST /api/admin/user-secrets/balances,requireAdmin +
DataReadScope 逐个剔除越权 userId(不信任前端给的列表)。三条护栏是这条路线不被点爆的唯一防线:单次 ≤20 行
(越限 BusinessException,不静默截断)、固定线程池 adminBalanceConcurrency=4 + 整请求 deadline 10s(到点的行
按「上游未在本轮时间预算内应答」降级并记进 timedOutUserIds 如实上报,不读成 0)、只对真能查的行打上游
(LLM 仅 longtaitou、代理仅 detectFromUrl==JIKIP;t8star/青果零 HTTP),一页 15 行通常只剩 3–8 次调用。
用户端 GET /api/user-secrets/llm-balance?moduleKey= 与既有 proxy-balance 同款 requireUser。
保存/清空密钥与后台代填/清空时代际失效两侧余额缓存:换一把钥匙还挂着上一把的钱就是串档。
配置三键同步 application.yml 与 application-local.example.yml(铁律 3)。
测试:LongtaitouBalanceClientTest 11(官方样例断言 balance=="88.888882"/surplus=="85.288882" 且 12.34/11.84/0.50/$
一律不出现;缺 credits、per_usd<=0、unit≠CREDIT、缺 available 四种坏形状各自 available=false + balance=null;
现网实测 401 missing_api_key / invalid_api_key 形状入夹具——钉的是测过的读数不是猜的错误体)、
UserLlmBalanceServiceTest 10(贞贞 never() 打上游、三态不伪装成 0、缓存命中不二次查询、两模块各回各值)、
UserSecretBalanceAdminServiceTest 7(越上限拒、越权剔、超时行 available=false 而非 0、只有可查行产生 HTTP)。
三支已登记进 ops scripts/score_ratchet.py 的 suites(不入册=闸门永远跑不到)。
catch 棘轮五枚新增全是 NOT_RETHROW(LOG_ONLY/EMPTY 一格没涨),逐处记名抬 STRICT_TOTAL 1065→1069、
notRethrow 604→608。未证事项按 BACKLOG B83-01 如实挂:真 sk- 下 credits 字段逐字核对、后管实时查的现网
并发表现、jikip find-balance 对用户自有套餐 key;本窗代码未随任何 jar 发版。
---
.../aiimage/config/UserSecretProperties.java | 13 +
.../client/LongtaitouBalanceClient.java | 244 ++++++++++++++++++
.../AdminUserApiSecretController.java | 22 +-
.../controller/UserApiSecretController.java | 29 ++-
.../dto/AdminUserSecretBalanceQuery.java | 23 ++
.../model/vo/AdminUserSecretBalancesVo.java | 41 +++
.../usersecret/model/vo/UserLlmBalanceVo.java | 53 ++++
.../service/UserLlmBalanceService.java | 137 ++++++++++
.../UserSecretBalanceAdminService.java | 225 ++++++++++++++++
.../resources/application-local.example.yml | 8 +
.../src/main/resources/application.yml | 7 +
.../config/CatchSilenceRatchetTest.java | 21 +-
.../client/LongtaitouBalanceClientTest.java | 180 +++++++++++++
.../service/UserLlmBalanceServiceTest.java | 189 ++++++++++++++
.../UserSecretBalanceAdminServiceTest.java | 195 ++++++++++++++
15 files changed, 1381 insertions(+), 6 deletions(-)
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClient.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/AdminUserSecretBalanceQuery.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretBalancesVo.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserLlmBalanceVo.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceService.java
create mode 100644 backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminService.java
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClientTest.java
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceServiceTest.java
create mode 100644 backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminServiceTest.java
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
index b729d2e53..a0597dd45 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
@@ -41,6 +41,19 @@ public class UserSecretProperties {
/** jikip 余量查询接口(客户端设置弹窗展示套餐 IP 余量 / 账户余额)。 */
private String jikipBalanceUrl = "https://api.jikip.com/find-balance";
+ /**
+ * 龙抬头余额查询接口(密钥设置与后台列表展示人民币余额)。
+ * 留空即按登记的渠道主机派生({@code LlmChannel.LONGTAITOU.host() + /v1/skills/balance}),
+ * 所以这里出厂为空串而不是抄一份域名:域名有两个出处就会漂(10-30 那次「发布域名红线」同款教训)。
+ */
+ private String longtaitouBalanceUrl = "";
+
+ /** 后台密钥列表刷新余额时的并发上限(再高就是拿后管页去压上游,限流会整页超时)。 */
+ private int adminBalanceConcurrency = 4;
+
+ /** 后台密钥列表刷新余额的整请求时间预算(毫秒);到点未回的行如实报「没应答」,不报 0。 */
+ private long adminBalanceDeadlineMillis = 10_000L;
+
/** jikip 白名单检测接口:?id=套餐id&ip=待检测IP,data=1 表示已在白名单。 */
private String jikipWhiteListCheckUrl = "https://api.jikip.com/whiteList-check";
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClient.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClient.java
new file mode 100644
index 000000000..ff1d7e50e
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClient.java
@@ -0,0 +1,244 @@
+package com.nanri.aiimage.modules.usersecret.client;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.nanri.aiimage.common.text.UserMessages;
+import com.nanri.aiimage.config.HttpClientPool;
+import com.nanri.aiimage.config.UserSecretProperties;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
+import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestClient;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.time.Duration;
+import java.time.LocalDateTime;
+
+/**
+ * 龙抬头开放接口的余额客户端:{@code GET /v1/skills/balance}。
+ *
+ *
只认 {@code credits} 块。上游同一份响应里给了两套口径:顶层
+ * {@code balance / frozen / available_balance} 是美元串(形如 {@code "$12.345678"},
+ * 带 {@code $} 前缀、6 位小数),{@code credits} 才是站内展示的 ⚡=人民币口径
+ * (⚡=美元 × {@code credits.per_usd})。要跟用户看到的网页/账单对上必须用 {@code credits};
+ * 而 {@code credits} 缺失时不许退回顶层美元串——把 {@code $12.34} 显示成 {@code ¥12.34}
+ * 是「数字看着正常、含义是错的」那一类错,比一句「查不到」难发现得多。
+ *
+ * 因此这里不做任何汇率换算(代码里出现汇率字面量就等于自己造了一套口径),
+ * 也只把 {@code credits} 的值放进 VO——美元数字根本不进返回体,前端拿不到,也就没法误用。
+ *
+ * 失败一律降级成 {@code available=false} 并原样带上原因,绝不抛出中断调用方(与
+ * {@link JikipProxyClient} 同形)。
+ */
+@Component
+@Slf4j
+public class LongtaitouBalanceClient {
+
+ private static final int BALANCE_READ_TIMEOUT_MILLIS = 8_000;
+ private static final int MAX_RESPONSE_BYTES = 1 << 20;
+ private static final String BALANCE_PATH = "/v1/skills/balance";
+ /** {@code credits.unit} 的登记值;不是这个值说明上游改了口径而我们还没跟着改,宁可不显示。 */
+ static final String CREDIT_UNIT = "CREDIT";
+ /** 交叉校验容差:⚡ 与 美元×per_usd 的相对偏差超过它只记日志,仍按 credits 展示。 */
+ private static final double CROSS_CHECK_TOLERANCE = 0.005;
+
+ private final UserSecretProperties properties;
+ private final ObjectMapper objectMapper;
+
+ private volatile RestClient sharedClient;
+
+ public LongtaitouBalanceClient(UserSecretProperties properties, ObjectMapper objectMapper) {
+ this.properties = properties;
+ this.objectMapper = objectMapper;
+ }
+
+ /** 余额查询地址:配置项优先,留空时按渠道登记的 host 派生(不在这里写死域名)。 */
+ String balanceUrl() {
+ String configured = normalize(properties.getLongtaitouBalanceUrl());
+ return configured.isEmpty() ? LlmChannel.LONGTAITOU.host() + BALANCE_PATH : configured;
+ }
+
+ /**
+ * 查一次余额。{@code plainApiKey} 是服务端已存的明文密钥(前端手里没有明文,只能由服务端查)。
+ * 上游约 5 秒缓存同一把密钥的余额,所以重复查询不额外付费。
+ */
+ public UserLlmBalanceVo fetch(String plainApiKey) {
+ UserLlmBalanceVo vo = new UserLlmBalanceVo();
+ vo.setChannel(LlmChannel.LONGTAITOU.key());
+ vo.setChannelLabel(LlmChannel.LONGTAITOU.label());
+ String key = stripBearer(plainApiKey);
+ if (key.isEmpty()) {
+ vo.setAvailable(false);
+ vo.setMessage("未配置龙抬头密钥");
+ return vo;
+ }
+ try {
+ StatusAndBody response = restClient().get()
+ .uri(balanceUrl())
+ .headers(headers -> headers.setBearerAuth(key))
+ .exchange((request, res) -> new StatusAndBody(
+ res.getStatusCode().value(),
+ readBodyBounded(res.getBody())));
+ return parseResponse(vo, response.statusCode(), response.body());
+ } catch (Exception ex) {
+ log.warn("[user-secret][llm-balance] 龙抬头余额查询异常 err={}", ex.getMessage());
+ vo.setAvailable(false);
+ vo.setMessage(UserMessages.with("余额查询失败", ex));
+ return vo;
+ }
+ }
+
+ /** 把一次应答换成可展示的余额(与网络分离,判据可以不打上游直接钉解析形状)。 */
+ UserLlmBalanceVo parseResponse(UserLlmBalanceVo vo, int statusCode, String body) {
+ JsonNode root = parseJson(body);
+ if (statusCode < 200 || statusCode >= 300) {
+ vo.setAvailable(false);
+ vo.setMessage(upstreamMessage(root, statusCode));
+ log.warn("[user-secret][llm-balance] 龙抬头余额查询被拒 httpStatus={}", statusCode);
+ return vo;
+ }
+ if (root == null) {
+ vo.setAvailable(false);
+ vo.setMessage("龙抬头余额接口返回的不是可解析的 JSON");
+ return vo;
+ }
+ return applyCredits(vo, root);
+ }
+
+ /**
+ * 从 {@code credits} 块取人民币口径;拿不到就是拿不到,不回落美元。
+ *
+ * 容许 {@code credits.frozen} 缺失(进行中任务没有预冻结时上游可能省略),但
+ * {@code balance} 与 {@code available} 缺任一都不算成功——只有一半的余额数字更容易被读成「另一部分是 0」。
+ */
+ private UserLlmBalanceVo applyCredits(UserLlmBalanceVo vo, JsonNode root) {
+ JsonNode credits = root.path("credits");
+ String unit = text(credits.get("unit"));
+ double perUsd = credits.path("per_usd").asDouble(Double.NaN);
+ String total = decimalText(credits.get("balance"));
+ String available = decimalText(credits.get("available"));
+ if (!credits.isObject() || !CREDIT_UNIT.equalsIgnoreCase(nullToEmpty(unit))
+ || !(perUsd > 0) || total == null || available == null) {
+ vo.setAvailable(false);
+ vo.setMessage("龙抬头没有返回人民币(⚡)口径的余额块,为避免把美元数字当人民币显示,这里不给金额");
+ log.warn("[user-secret][llm-balance] credits 块不合格 unit={} perUsd={} 是否含 balance={}",
+ unit, perUsd, total != null);
+ return vo;
+ }
+ vo.setBalance(total);
+ vo.setAvailableBalance(available);
+ vo.setFrozen(decimalText(credits.get("frozen")));
+ vo.setUnit(CREDIT_UNIT);
+ vo.setAvailable(true);
+ vo.setCheckedAt(LocalDateTime.now());
+ crossCheck(root, total, perUsd);
+ return vo;
+ }
+
+ /** 美元 × per_usd 与 credits.balance 背离时只记账,不改展示口径(credits 才是账单上那个数)。 */
+ private void crossCheck(JsonNode root, String creditsBalance, double perUsd) {
+ Double usd = parseUsd(text(root.get("balance")));
+ if (usd == null) {
+ return;
+ }
+ double expected = usd * perUsd;
+ double actual = Double.parseDouble(creditsBalance);
+ if (expected <= 0 || actual <= 0) {
+ return;
+ }
+ double deviation = Math.abs(expected - actual) / Math.max(expected, actual);
+ if (deviation > CROSS_CHECK_TOLERANCE) {
+ log.warn("[user-secret][llm-balance] 上游两套口径背离(美元×per_usd 与 credits 不一致,比例 {}),"
+ + "仍按 credits 展示", String.format("%.4f", deviation));
+ }
+ }
+
+ /** 顶层美元串形如 {@code "$12.345678"}:去掉 {@code $} 前缀后取数,仅用于交叉校验。 */
+ private static Double parseUsd(String raw) {
+ String text = nullToEmpty(raw).replace("$", "").replace(",", "").trim();
+ if (text.isEmpty()) {
+ return null;
+ }
+ try {
+ return Double.parseDouble(text);
+ } catch (NumberFormatException ex) {
+ return null;
+ }
+ }
+
+ /** 上游错误体 {@code {error:{code,message,type,class}}}:优先给它的人话,否则给状态码。 */
+ private String upstreamMessage(JsonNode root, int statusCode) {
+ if (root != null) {
+ JsonNode error = root.path("error");
+ String message = text(error.get("message"));
+ if (message != null && !message.isBlank()) {
+ String code = text(error.get("code"));
+ return code == null || code.isBlank() ? message : message + "(" + code + ")";
+ }
+ }
+ return "龙抬头余额接口返回 HTTP " + statusCode + ",请稍后重试";
+ }
+
+ /** 数字节点保持上游原样文本({@code 88.888882} 不许先四舍五入——账单对不上时无从回溯)。 */
+ private static String decimalText(JsonNode node) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return null;
+ }
+ if (node.isNumber() || node.isTextual()) {
+ String text = node.asText().trim();
+ return text.isEmpty() ? null : text;
+ }
+ return null;
+ }
+
+ private RestClient restClient() {
+ RestClient client = sharedClient;
+ if (client != null) {
+ return client;
+ }
+ synchronized (this) {
+ if (sharedClient == null) {
+ sharedClient = RestClient.builder()
+ .requestFactory(HttpClientPool.requestFactory(BALANCE_READ_TIMEOUT_MILLIS))
+ .build();
+ }
+ return sharedClient;
+ }
+ }
+
+ /** 探测响应体的读取界:JDK 的 readTimeout 只封顶到响应头,断流时这一读会永久 park。 */
+ private String readBodyBounded(InputStream inputStream) throws IOException {
+ return HttpClientPool.readBodyBounded(inputStream,
+ Duration.ofMillis(BALANCE_READ_TIMEOUT_MILLIS), MAX_RESPONSE_BYTES);
+ }
+
+ private JsonNode parseJson(String body) {
+ try {
+ return body == null || body.isBlank() ? null : objectMapper.readTree(body);
+ } catch (Exception ex) {
+ return null;
+ }
+ }
+
+ private static String stripBearer(String token) {
+ String normalized = normalize(token);
+ return normalized.regionMatches(true, 0, "Bearer ", 0, 7) ? normalized.substring(7).trim() : normalized;
+ }
+
+ private static String text(JsonNode node) {
+ return node == null || node.isNull() || node.isMissingNode() ? null : node.asText();
+ }
+
+ private static String nullToEmpty(String value) {
+ return value == null ? "" : value.trim();
+ }
+
+ private static String normalize(String value) {
+ return value == null ? "" : value.trim();
+ }
+
+ private record StatusAndBody(int statusCode, String body) {
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java
index a4fbfa49e..7cb3dfc2b 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/AdminUserApiSecretController.java
@@ -7,12 +7,15 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
+import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretBalanceQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
+import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretBalancesVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretPageVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
+import com.nanri.aiimage.modules.usersecret.service.UserSecretBalanceAdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -45,6 +48,7 @@ public class AdminUserApiSecretController {
private final UserApiSecretService userApiSecretService;
private final UserSecretProperties userSecretProperties;
+ private final UserSecretBalanceAdminService userSecretBalanceAdminService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@@ -79,6 +83,18 @@ public class AdminUserApiSecretController {
return ApiResponse.success("检测完成", userApiSecretService.adminCheckByUser(userId));
}
+ @PostMapping("/balances")
+ @Operation(summary = "刷新本页用户的余额侧写",
+ description = "实时打上游(龙抬头人民币余额=credits 块;极客代理余量=find-balance),**不落库**。"
+ + "单次最多 20 个用户、固定并发与整请求时间预算;到点没回的行如实报「上游未应答」,不报 0。"
+ + "请求里的 userId 不是安全边界:一律按数据权限收窄,被剔的 id 在 deniedUserIds 里回传。")
+ public ApiResponse balances(
+ HttpServletRequest request,
+ @RequestBody AdminUserSecretBalanceQuery body) {
+ AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
+ return ApiResponse.success(userSecretBalanceAdminService.balances(operator, body));
+ }
+
@DeleteMapping("/{userId}")
@Operation(summary = "清空该用户全部密钥与代理配置")
public ApiResponse clear(
@@ -98,8 +114,10 @@ public class AdminUserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
- return ApiResponse.success("已代填并锁定",
- userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue(), body.getChannel()));
+ AdminUserSecretModuleVo vo = userApiSecretService.adminSaveModule(
+ operator, userId, moduleKey, body.getValue(), body.getChannel());
+ userSecretBalanceAdminService.invalidate(userId);
+ return ApiResponse.success("已代填并锁定", vo);
}
@DeleteMapping("/{userId}/modules/{moduleKey}")
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
index 1a3ea2597..86f0f27b3 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
@@ -15,8 +15,10 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserClientIpVo;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
+import com.nanri.aiimage.modules.usersecret.service.UserLlmBalanceService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyBalanceService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyPlanService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyWhitelistService;
@@ -34,8 +36,10 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
+import java.util.List;
import java.util.Map;
/**
@@ -51,6 +55,7 @@ public class UserApiSecretController {
private final UserApiSecretService userApiSecretService;
private final UserProxyPlanService userProxyPlanService;
private final UserProxyBalanceService userProxyBalanceService;
+ private final UserLlmBalanceService userLlmBalanceService;
private final UserProxyWhitelistService userProxyWhitelistService;
private final AdminAuthSupport adminAuthSupport;
@@ -69,7 +74,11 @@ public class UserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
Long userId = currentUserId(request);
- return ApiResponse.success("保存成功", userApiSecretService.save(userId, moduleKey, body.getValue(), body.getChannel()));
+ UserApiSecretItemVo vo = userApiSecretService.save(userId, moduleKey, body.getValue(), body.getChannel());
+ // 换钥匙必须先把旧钥匙的余额丢掉:否则面板会把上一把 key 的钱挂在新 key/新渠道名下(串档形状)
+ userLlmBalanceService.invalidate(userId);
+ userProxyBalanceService.invalidate(userId);
+ return ApiResponse.success("保存成功", vo);
}
@DeleteMapping("/{moduleKey}")
@@ -79,6 +88,8 @@ public class UserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey) {
Long userId = currentUserId(request);
userApiSecretService.clear(userId, moduleKey);
+ userLlmBalanceService.invalidate(userId);
+ userProxyBalanceService.invalidate(userId);
return ApiResponse.success("已清空", null);
}
@@ -113,6 +124,22 @@ public class UserApiSecretController {
return ApiResponse.success(userProxyBalanceService.balance(userId));
}
+ @GetMapping("/llm-balance")
+ @Operation(summary = "查询 LLM 渠道余额(人民币口径)",
+ description = "龙抬头 /v1/skills/balance 的 credits 块(站内 ⚡=人民币);"
+ + "moduleKey 为空时一次回齐两张 LLM 密钥卡。贞贞渠道不提供余额查询,如实回「查不了」,"
+ + "不借别家的数、也不显示成 0。")
+ public ApiResponse> llmBalance(
+ HttpServletRequest request,
+ @Parameter(description = "密钥模块 key;留空=两张 LLM 卡都要")
+ @RequestParam(required = false) String moduleKey) {
+ Long userId = currentUserId(request);
+ if (moduleKey == null || moduleKey.isBlank()) {
+ return ApiResponse.success(userLlmBalanceService.bundle(userId));
+ }
+ return ApiResponse.success(List.of(userLlmBalanceService.balance(userId, moduleKey)));
+ }
+
@GetMapping("/proxy-plan")
@Operation(summary = "读取当前用户的 jikip 套餐配置")
public ApiResponse proxyPlan(HttpServletRequest request) {
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/AdminUserSecretBalanceQuery.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/AdminUserSecretBalanceQuery.java
new file mode 100644
index 000000000..537de61f0
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/AdminUserSecretBalanceQuery.java
@@ -0,0 +1,23 @@
+package com.nanri.aiimage.modules.usersecret.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * 后台密钥管理列表的余额刷新请求:只带本页可见的用户 ID,不接受「全部用户」。
+ */
+@Data
+@Schema(description = "后台余额刷新请求")
+public class AdminUserSecretBalanceQuery {
+
+ @Schema(description = "要刷新余额的用户 ID(本页行;单次上限见服务端校验)")
+ private List userIds;
+
+ /** 公司 tab 走 snake_case,与这一页的请求侧既有写法同形({@code company_id} 被尺子钉着)。 */
+ @JsonProperty("company_id")
+ @Schema(description = "公司 tab(只收窄、不放大;非超管一律按会话裁剪)")
+ private Long companyId;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretBalancesVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretBalancesVo.java
new file mode 100644
index 000000000..925c42b64
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/AdminUserSecretBalancesVo.java
@@ -0,0 +1,41 @@
+package com.nanri.aiimage.modules.usersecret.model.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * 后台密钥管理列表的余额侧写:与列表行**分开发**(列表本身零额外 SQL、零上游调用)。
+ *
+ * 这里的数是**取数时刻的快照**({@code UserLlmBalanceVo.checkedAt} 带在每格里),不是库里的列:
+ * 后台不落余额快照,是为了不在每行加一次跨用户循环写、也不让界面读到几小时前的陈值。
+ */
+@Data
+@Schema(description = "后台密钥管理-按用户回传的余额")
+public class AdminUserSecretBalancesVo {
+
+ @Schema(description = "逐用户的余额(顺序不保证与请求一致,前端按 userId 对号)")
+ private List- items;
+
+ @Schema(description = "被数据权限剔出、本次没有查的用户 ID(不静默少给数)")
+ private List deniedUserIds;
+
+ @Schema(description = "因超出整请求时间预算而没有取到数的用户 ID")
+ private List timedOutUserIds;
+
+ /** 一行的余额:两把 LLM 卡各有各的钱,代理余量另算一档。 */
+ @Data
+ @Schema(description = "单用户余额侧写")
+ public static class Item {
+
+ @Schema(description = "用户 ID")
+ private Long userId;
+
+ @Schema(description = "LLM 余额(外观专利/货源查询各一条,人民币口径)")
+ private List llm;
+
+ @Schema(description = "代理余量(jikip 套餐口径;青果为 scope=none,平台池为 scope=platform)")
+ private UserApiSecretBalanceVo proxy;
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserLlmBalanceVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserLlmBalanceVo.java
new file mode 100644
index 000000000..930d57b3b
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserLlmBalanceVo.java
@@ -0,0 +1,53 @@
+package com.nanri.aiimage.modules.usersecret.model.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * LLM 渠道余额(龙抬头)。
+ *
+ *
刻意与 {@link UserApiSecretBalanceVo} 分开:那一个的 {@code surplus / scope / low} 全是
+ * jikip 代理套餐的语义({@code surplus}=套餐剩余 IP 次数、{@code scope}=user/platform),
+ * 把 LLM 的人民币余额塞进去,等于让同一个字段名在两处表示两种东西——铁律 25 说的「口径不得借」
+ * 防的正是这个(青果曾在这里显示成别人家的 jikip 余量)。
+ */
+@Data
+@Schema(description = "LLM 渠道余额(人民币口径)")
+public class UserLlmBalanceVo {
+
+ @Schema(description = "密钥模块 key(appearance-patent / similar-asin)")
+ private String moduleKey;
+
+ @Schema(description = "密钥模块显示名")
+ private String moduleLabel;
+
+ @Schema(description = "渠道 key:longtaitou / t8star")
+ private String channel;
+
+ @Schema(description = "渠道显示名")
+ private String channelLabel;
+
+ @Schema(description = "是否拿到了可展示的余额")
+ private Boolean available;
+
+ @Schema(description = "总余额,人民币(⚡)口径的上游原样小数串(未取整,界面负责显示精度);"
+ + "available=false 时为空")
+ private String balance;
+
+ @Schema(description = "可用余额(人民币=总余额-进行中任务的预冻结)")
+ private String availableBalance;
+
+ @Schema(description = "预冻结金额(人民币)")
+ private String frozen;
+
+ @Schema(description = "金额单位,恒为 CREDIT(龙抬头站内 ⚡=人民币口径)")
+ private String unit;
+
+ @Schema(description = "查不到时的原因(available=false 时);前端原样展示,不再加工")
+ private String message;
+
+ @Schema(description = "本次取数时刻(内存缓存内复用 5 分钟,界面据此显示「更新于」)")
+ private LocalDateTime checkedAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceService.java
new file mode 100644
index 000000000..c3d6f6ae4
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceService.java
@@ -0,0 +1,137 @@
+package com.nanri.aiimage.modules.usersecret.service;
+
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.modules.usersecret.client.LongtaitouBalanceClient;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
+import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
+import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * LLM 渠道余额:桌面端「密钥设置」的 LLM 卡与后台密钥管理列表共用这一处取数。
+ *
+ * 与 {@link UserProxyBalanceService} 分开成类,两条理由都记在这儿:① 缓存键不同
+ * (这里是 {@code (userId, moduleKey)}——同一账号两把 LLM 密钥各有各的余额;那边是 {@code userId}
+ * 单键,因为一个用户只有一套代理套餐);② 铁律 25「余量口径不得借」——两套语义装进一个类,
+ * 注释迟早撒谎,而下一个人会照着撒谎的注释加分支。
+ *
+ * 为什么渠道判据读 {@code findChannel} 而不是另解析一次:这一列值就是任务执行时
+ * 真正发请求用的那个渠道({@code UserApiSecretService#resolveLlmHost} 取的是同一个源)。
+ * 闸门与展示各读各的会出现「界面说龙抬头、任务其实发贞贞」,所以铁律 27(a) 要求同源。
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class UserLlmBalanceService {
+
+ /** 上游自己约 5 秒缓存同一把密钥的余额;这里再叠一层,是为了让后台列表翻页不逐页打上游。 */
+ private static final long CACHE_MILLIS = 5 * 60 * 1000L;
+
+ /** key={@code userId|moduleKey};改/清/切渠道时按 userId 整批失效。 */
+ private final Map cache = new ConcurrentHashMap<>();
+
+ private final UserApiSecretService userApiSecretService;
+ private final LongtaitouBalanceClient longtaitouBalanceClient;
+
+ /** 桌面端单卡取数:{@code moduleKey} 必须是 LLM 模块(代理模块走 {@link UserProxyBalanceService})。 */
+ public UserLlmBalanceVo balance(Long userId, String moduleKey) {
+ UserSecretModule module = requireLlmModule(userId, moduleKey);
+ String cacheKey = cacheKey(userId, module.key());
+ long now = System.currentTimeMillis();
+ CachedLlmBalance cached = cache.get(cacheKey);
+ if (cached != null && now - cached.cachedAtMillis() < CACHE_MILLIS) {
+ return cached.balance();
+ }
+ UserLlmBalanceVo vo = loadOne(userId, module);
+ cache.put(cacheKey, new CachedLlmBalance(vo, System.currentTimeMillis()));
+ return vo;
+ }
+
+ /**
+ * 桌面端一次拿齐两张 LLM 卡(外观专利/货源查询)。清单唯一来源是
+ * {@link UserSecretModule#requiredModules()}——与密钥包下发、桌面端完整性门禁同一处,
+ * 不在这里另列一张表。
+ */
+ public List bundle(Long userId) {
+ List items = new ArrayList<>();
+ for (UserSecretModule module : UserSecretModule.requiredModules()) {
+ items.add(balance(userId, module.key()));
+ }
+ return items;
+ }
+
+ /** 改了/清了/切了任一 LLM 渠道配置后调用:下一次查询立即按新配置走,不复用旧余额。 */
+ public void invalidate(Long userId) {
+ if (userId == null) {
+ return;
+ }
+ String prefix = userId + "|";
+ cache.keySet().removeIf(key -> key.startsWith(prefix));
+ }
+
+ private UserLlmBalanceVo loadOne(Long userId, UserSecretModule module) {
+ UserLlmBalanceVo vo = new UserLlmBalanceVo();
+ vo.setModuleKey(module.key());
+ vo.setModuleLabel(module.label());
+ String channelKey = userApiSecretService.findChannel(userId, module.key());
+ vo.setChannel(channelKey);
+ vo.setChannelLabel(LlmChannel.of(channelKey).label());
+ if (!LlmChannel.LONGTAITOU.key().equals(channelKey)) {
+ return channelUnsupported(vo, module);
+ }
+ String plain = userApiSecretService.findPlainValue(userId, module.key());
+ if (plain == null || plain.isBlank()) {
+ vo.setAvailable(false);
+ vo.setMessage("这一项还没配置龙抬头密钥,配好并保存后才能查余额");
+ return vo;
+ }
+ UserLlmBalanceVo fetched = longtaitouBalanceClient.fetch(plain);
+ fetched.setModuleKey(module.key());
+ fetched.setModuleLabel(module.label());
+ return fetched;
+ }
+
+ /**
+ * 贞贞档的余额答复:不打上游、不借龙抬头的数。
+ *
+ * 贞贞有没有可用的余额端点在册无判据(龙抬头那份文档讲的是它自己家)。照青果那一档
+ * 的先例({@code UserProxyBalanceService#qingguoUnsupported}):宁可说「查不了」,
+ * 也不许猜一个端点、更不许把别家的钱挂在这一行上。
+ */
+ private UserLlmBalanceVo channelUnsupported(UserLlmBalanceVo vo, UserSecretModule module) {
+ vo.setAvailable(false);
+ vo.setMessage(vo.getChannelLabel() + "渠道不提供余额查询;用量请看 "
+ + LlmChannel.of(vo.getChannel()).host().replaceFirst("^https?://", "")
+ + " 自己的控制台。密钥是否正常请点「检测」。");
+ return vo;
+ }
+
+ private UserSecretModule requireLlmModule(Long userId, String moduleKey) {
+ if (userId == null || userId <= 0) {
+ throw new BusinessException("用户 ID 不合法");
+ }
+ Optional module = UserSecretModule.of(moduleKey);
+ if (module.isEmpty()) {
+ throw new BusinessException("未知的密钥模块:" + (moduleKey == null ? "" : moduleKey.trim()));
+ }
+ if (module.get().isProxy()) {
+ throw new BusinessException("代理设置走「代理余量」,不是 LLM 余额");
+ }
+ return module.get();
+ }
+
+ private static String cacheKey(Long userId, String moduleKey) {
+ return userId + "|" + moduleKey;
+ }
+
+ private record CachedLlmBalance(UserLlmBalanceVo balance, long cachedAtMillis) {
+ }
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminService.java
new file mode 100644
index 000000000..5ac75f093
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminService.java
@@ -0,0 +1,225 @@
+package com.nanri.aiimage.modules.usersecret.service;
+
+import com.nanri.aiimage.common.exception.BusinessException;
+import com.nanri.aiimage.common.model.entity.AdminUserEntity;
+import com.nanri.aiimage.common.service.DataReadScope;
+import com.nanri.aiimage.common.service.ReadScope;
+import com.nanri.aiimage.config.UserSecretProperties;
+import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretBalanceQuery;
+import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretBalancesVo;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
+import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+/**
+ * 后台密钥管理列表的余额侧写:**实时打上游、不落库**。
+ *
+ * 列表本身({@code UserApiSecretService#adminPage})一次 {@code selectList} 组行,
+ * 本类只在其后按本页用户补数,所以不引入任何新的 SQL 或 N+1 查库。
+ *
+ * 三条护栏是这条路线的全部安全性(少一条,翻页就会变成打上游的洪水):
+ *
+ * - 单次调用上限 {@link #MAX_ROWS_PER_CALL} 个用户——超出直接拒,不做静默截断;
+ * - 固定并发 + 整请求时间预算:到点没回的行如实降级成 {@code available=false}
+ * 并写明「上游未在预算内应答」,绝不降级成 0 或空表;
+ * - 数据权限剔行:请求里带的 userId 一律按 {@link DataReadScope} 收窄,
+ * 越权的 id 不查、并回传在 {@code deniedUserIds} 里(不静默少给数)。
+ * 前端给的 userId 列表不是安全边界。
+ *
+ *
+ * 真正会发 HTTP 的行比请求行数少得多:非龙抬头渠道({@code UserLlmBalanceService})
+ * 与青果供应商({@code UserProxyBalanceService})都在各自服务里直接判「不提供查询」,
+ * 一次上游都不打;再加上两处 5 分钟内存缓存,翻页与反复点刷新不会逐次付费。
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class UserSecretBalanceAdminService {
+
+ /** 单次调用允许刷新的用户数上限:15(默认页)留一倍余量,pageSize=100 时由前端分批请求。 */
+ static final int MAX_ROWS_PER_CALL = 20;
+
+ /** 线程池并发上限:再多就是拿后管页去压上游,供应商侧限流会把整页一起拖成超时。 */
+ private static final int MAX_CONCURRENCY = 8;
+
+ private final UserLlmBalanceService userLlmBalanceService;
+ private final UserProxyBalanceService userProxyBalanceService;
+ private final DataReadScope dataReadScope;
+ private final UserSecretProperties userSecretProperties;
+
+ public AdminUserSecretBalancesVo balances(AdminUserEntity operator, AdminUserSecretBalanceQuery query) {
+ AdminUserSecretBalancesVo result = new AdminUserSecretBalancesVo();
+ List requested = distinct(query == null ? null : query.getUserIds());
+ if (requested.isEmpty()) {
+ result.setItems(List.of());
+ result.setDeniedUserIds(List.of());
+ result.setTimedOutUserIds(List.of());
+ return result;
+ }
+ if (requested.size() > MAX_ROWS_PER_CALL) {
+ throw new BusinessException("一次最多刷新 " + MAX_ROWS_PER_CALL + " 个用户的余额,"
+ + "请调小「每页数量」或翻页刷新");
+ }
+ ReadScope scope = dataReadScope.readScope(operator, query.getCompanyId());
+ List allowed = scope.userIdsOr(requested);
+ List denied = new ArrayList<>(requested);
+ denied.removeAll(allowed);
+
+ Map items = new ConcurrentHashMap<>();
+ for (Long userId : allowed) {
+ AdminUserSecretBalancesVo.Item item = new AdminUserSecretBalancesVo.Item();
+ item.setUserId(userId);
+ List modules = UserSecretModule.requiredModules();
+ List llm = new ArrayList<>(modules.size());
+ for (int i = 0; i < modules.size(); i++) {
+ llm.add(i, null);
+ }
+ item.setLlm(llm);
+ items.put(userId, item);
+ }
+
+ Set timedOut = new LinkedHashSet<>();
+ int concurrency = Math.min(Math.max(1, userSecretProperties.getAdminBalanceConcurrency()), MAX_CONCURRENCY);
+ long deadlineMillis = Math.max(1_000L, userSecretProperties.getAdminBalanceDeadlineMillis());
+ ExecutorService pool = Executors.newFixedThreadPool(concurrency);
+ List pendings = new ArrayList<>();
+ try {
+ for (Long userId : allowed) {
+ List modules = UserSecretModule.requiredModules();
+ for (int index = 0; index < modules.size(); index++) {
+ UserSecretModule module = modules.get(index);
+ int slot = index;
+ pendings.add(new Pending(userId, module.key(),
+ pool.submit(() -> userLlmBalanceService.balance(userId, module.key())),
+ value -> items.get(userId).getLlm().set(slot, (UserLlmBalanceVo) value),
+ () -> timedOutLlm(module)));
+ }
+ pendings.add(new Pending(userId, null,
+ pool.submit(() -> userProxyBalanceService.balance(userId)),
+ value -> items.get(userId).setProxy((UserApiSecretBalanceVo) value),
+ UserSecretBalanceAdminService::timedOutProxy));
+ }
+ long deadlineAt = System.currentTimeMillis() + deadlineMillis;
+ for (Pending pending : pendings) {
+ long remaining = Math.max(1L, deadlineAt - System.currentTimeMillis());
+ try {
+ pending.apply().accept(pending.future().get(remaining, TimeUnit.MILLISECONDS));
+ } catch (TimeoutException ex) {
+ pending.future().cancel(true);
+ pending.apply().accept(pending.degraded().get());
+ timedOut.add(pending.userId());
+ } catch (ExecutionException | InterruptedException ex) {
+ if (ex instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ pending.apply().accept(pending.degraded().get());
+ timedOut.add(pending.userId());
+ log.warn("[user-secret][admin-balance] 余额取数失败 userId={} module={} err={}",
+ pending.userId(), pending.moduleKey(), ex.getMessage());
+ }
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+
+ List ordered = new ArrayList<>();
+ for (Long userId : allowed) {
+ AdminUserSecretBalancesVo.Item item = items.get(userId);
+ if (item != null) {
+ item.getLlm().replaceAll(slot -> slot == null ? unknownLlm() : slot);
+ if (item.getProxy() == null) {
+ item.setProxy(unknownProxy());
+ }
+ ordered.add(item);
+ }
+ }
+ result.setItems(ordered);
+ result.setDeniedUserIds(denied);
+ result.setTimedOutUserIds(new ArrayList<>(timedOut));
+ log.info("[user-secret][admin-balance] 余额侧写完成 请求={} 允许={} 越权剔除={} 超预算={} 并发={} 预算={}ms",
+ requested.size(), allowed.size(), denied.size(), timedOut.size(), concurrency, deadlineMillis);
+ return result;
+ }
+
+ /**
+ * 后台代填/清空某用户配置后调用:两族余额缓存一起丢掉。
+ *
+ * 不这么做会出现「管理员刚换了钥匙,列表这一格还是上一把 key 的钱」——与用户端保存后
+ * 必须失效是同一个串档形状,只是这里由本类统一收口({@code UserApiSecretService} 反向依赖
+ * 余额服务会成环)。
+ */
+ public void invalidate(Long userId) {
+ userLlmBalanceService.invalidate(userId);
+ userProxyBalanceService.invalidate(userId);
+ }
+
+ /** 等待单元:一个(用户 × 一个余额口径)。moduleKey 为 null 表示代理余量。 */
+ private record Pending(Long userId, String moduleKey, Future> future,
+ Consumer