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 查库。

+ * + *

三条护栏是这条路线的全部安全性(少一条,翻页就会变成打上游的洪水):

+ *
    + *
  1. 单次调用上限 {@link #MAX_ROWS_PER_CALL} 个用户——超出直接拒,不做静默截断;
  2. + *
  3. 固定并发 + 整请求时间预算:到点没回的行如实降级成 {@code available=false} + * 并写明「上游未在预算内应答」,绝不降级成 0 或空表;
  4. + *
  5. 数据权限剔行:请求里带的 userId 一律按 {@link DataReadScope} 收窄, + * 越权的 id 不查、并回传在 {@code deniedUserIds} 里(不静默少给数)。 + * 前端给的 userId 列表不是安全边界。
  6. + *
+ * + *

真正会发 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 apply, Supplier degraded) { + } + + private static UserLlmBalanceVo timedOutLlm(UserSecretModule module) { + UserLlmBalanceVo vo = new UserLlmBalanceVo(); + vo.setModuleKey(module.key()); + vo.setModuleLabel(module.label()); + vo.setAvailable(false); + vo.setMessage("上游未在本轮时间预算内应答,稍后重试;这不代表密钥失效,也不代表余额为 0"); + return vo; + } + + private static UserApiSecretBalanceVo timedOutProxy() { + UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo(); + vo.setAvailable(false); + vo.setScope("none"); + vo.setLow(false); + vo.setMessage("上游未在本轮时间预算内应答,稍后重试;这不代表余量为 0"); + return vo; + } + + private static UserLlmBalanceVo unknownLlm() { + UserLlmBalanceVo vo = new UserLlmBalanceVo(); + vo.setAvailable(false); + vo.setMessage("这一格没有取到数(不是余额为 0)"); + return vo; + } + + private static UserApiSecretBalanceVo unknownProxy() { + UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo(); + vo.setAvailable(false); + vo.setScope("none"); + vo.setLow(false); + vo.setMessage("这一格没有取到数(不是余量为 0)"); + return vo; + } + + private static List distinct(List ids) { + if (ids == null) { + return List.of(); + } + List out = new ArrayList<>(); + for (Long id : ids) { + if (id != null && id > 0 && !out.contains(id)) { + out.add(id); + } + } + return out; + } +} diff --git a/backend-java/src/main/resources/application-local.example.yml b/backend-java/src/main/resources/application-local.example.yml index f5b93b945..0f34a4865 100644 --- a/backend-java/src/main/resources/application-local.example.yml +++ b/backend-java/src/main/resources/application-local.example.yml @@ -104,6 +104,14 @@ AIIMAGE_NOTIFICATION_JIKIP_LOW_SURPLUS_THRESHOLD=100 # 账户余额 ≤ 阈值 → 管理员通知;供应商口径,0=关闭 AIIMAGE_NOTIFICATION_JIKIP_LOW_BALANCE_THRESHOLD=0 +# 龙抬头余额查询(人民币口径=credits 块,不是顶层那个 `$…` 美元串)。 +# 留空=按 LlmChannel.LONGTAITOU 的主机派生 `/v1/skills/balance`——域名只允许有一个出处,别在这里抄第二份。 +AIIMAGE_USER_SECRET_LONGTAITOU_BALANCE_URL= +# 后管「密钥管理」实时查上游的两条护栏(第三条是单次 ≤20 行,写在代码常量里)。 +# 这两个不是性能旋钮:没有它们,一个后管页面就能把上游点爆;而调小了只会把行读成「上游未应答」,不会读成 0。 +AIIMAGE_USER_SECRET_ADMIN_BALANCE_CONCURRENCY=4 +AIIMAGE_USER_SECRET_ADMIN_BALANCE_DEADLINE_MILLIS=10000 + # 以上 LLM 主机/模型是「贞贞」渠道的默认值(历史口径)。 # 2026-10-29 起用户密钥可按人选择渠道(龙抬头 / 贞贞,默认贞贞,可手动切龙抬头): # - 渠道主机写死在 UserSecretModule/LlmChannel 里,不读本段; diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml index 84848ed73..06be13291 100644 --- a/backend-java/src/main/resources/application.yml +++ b/backend-java/src/main/resources/application.yml @@ -600,6 +600,13 @@ aiimage: proxy-balance-check-budget-minutes: ${AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_BUDGET_MINUTES:10} proxy-balance-low-surplus-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_SURPLUS_THRESHOLD:100} proxy-balance-low-balance-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_BALANCE_THRESHOLD:0} + # 龙抬头余额查询地址:留空=按登记的渠道主机派生(LlmChannel.LONGTAITOU.host + /v1/skills/balance)。 + # 刻意不在此抄一份域名:域名有两个出处就会漂(发布域名红线那次就是这么踩的)。 + longtaitou-balance-url: ${AIIMAGE_USER_SECRET_LONGTAITOU_BALANCE_URL:} + # 后台密钥列表的余额侧写:实时打上游、不落库。这两个数是「别拿后管页去压上游」的护栏, + # 不是性能旋钮——并发再高只会让整页一起撞供应商限流。两侧各有 5 分钟内存缓存。 + admin-balance-concurrency: ${AIIMAGE_USER_SECRET_ADMIN_BALANCE_CONCURRENCY:4} + admin-balance-deadline-millis: ${AIIMAGE_USER_SECRET_ADMIN_BALANCE_DEADLINE_MILLIS:10000} # 巡检发现欠费/密钥失效时是否推送站内通知(铃铛) notify-enabled: ${AIIMAGE_USER_SECRET_NOTIFY_ENABLED:true} # 用量日统计保留期:取 400 天而非整年,避免跨年时把刚过期的上年数据删掉(含同比对比场景) diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java index 24367daea..21f42e88f 100644 --- a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java +++ b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java @@ -65,7 +65,9 @@ class CatchSilenceRatchetTest { // 10-31 CR 消项:证据保留期清理失败 WARN 兜底 + 任务号溢出回落 task_no,新增 2 处非抛分支,600 -> 602。 // 11-01 失败任务原任务重试:TaskInPlaceRetryService 的 clearResultError / resetAssembleJob // 两处 WARN 兜底,602 -> 604(logOnly 249 -> 251;严格格 STRICT_LOG_ONLY 190 -> 192)。 - static final int GIVEN_NOT_RETHROW = 604; + // 11-05 密钥余额三面(龙抬头 credits/后管实时查)抬 604 -> 608:五枚新增**全是 NOT_RETHROW**, + // LOG_ONLY 与 EMPTY 一格没涨(逐处记名见 STRICT_TOTAL 上方注释)——改的是"查不到"怎么表达,不是把它藏起来。 + static final int GIVEN_NOT_RETHROW = 608; static final int GIVEN_LOG_ONLY = 251; static final int GIVEN_EMPTY = 56; @@ -291,7 +293,18 @@ class CatchSilenceRatchetTest { // ② resetAssembleJob:复位组装作业失败只 WARN——同理,任务已复位,作业复位失败由 // stuck 扫描兜底,不该阻断用户点出来的这次重试。 // 反向对照:两处都不能改成「吞掉」——WARN 里带 taskId 与异常消息,出问题看得见。 - static final int STRICT_TOTAL = 1065; + // 11-05 密钥余额三面(龙抬头人民币余额 client/后管实时查余额)抬 1065 -> 1069,五枚全部 NOT_RETHROW, + // LOG_ONLY 与 EMPTY **一格没涨**——每一枚都把"这次没查到"换成界面读得出的状态,而不是只留一行日志: + // ① `LongtaitouBalanceClient.fetch`:网络/上游异常 ⇒ available=false +「余额查询失败」人话 + WARN。 + // 反向对照:改成往外抛=一次余额查询把设置页打成 500;改成静默 return=界面显示 ¥0(假绿)。 + // ② `LongtaitouBalanceClient.numberOrNull`:金额串(含 `$`/千分位)解析失败 ⇒ 返回 null ⇒ + // 上游 credits 不可解析就当"查不到"。这一枚是"美元当人民币"的闸门:回落顶层数字才是真事故。 + // ③ `LongtaitouBalanceClient.parseJson`:应答不是可解析 JSON ⇒ null,调用方给「返回的不是可解析的 JSON」。 + // ④ `UserSecretBalanceAdminService` 行等待 `TimeoutException`:cancel 该行的 future、该行按 + // 「上游未在本轮时间预算内应答」降级,并把 userId 记进 timedOutUserIds 如实上报(不得读成 0)。 + // ⑤ 同处 `ExecutionException | InterruptedException`:先复位中断位,再同样按"未应答"降级+记账+WARN。 + // 反向对照:④⑤ 若改成"超时给 0"或"catch 后什么都不记",后管那一列就会把"没问到"卖成"没钱"。 + static final int STRICT_TOTAL = 1069; /** * 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。 * 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。 @@ -417,7 +430,9 @@ class CatchSilenceRatchetTest { // 10-31 Phase 5.1:同 GIVEN_NOT_RETHROW,证据登记补偿回收失败只 WARN,599 -> 600。 // 11-01 失败任务原任务重试:TaskInPlaceRetryService 两处 WARN 兜底(clearResultError / // resetAssembleJob),严格口径实测 602 -> 604;出处见 STRICT_TOTAL 上方注释。 - static final int STRICT_NOT_RETHROW = 604; + // 11-05 密钥余额三面:五枚 NOT_RETHROW(1065->1069 那批),严格口径实测 603 -> 608; + // 上一格 604 是**上限**而实测量一直低它一枚,这次新增把那一枚额度用掉又超上去——逐处见 STRICT_TOTAL 上方。 + static final int STRICT_NOT_RETHROW = 608; /** * 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}: * 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出—— diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClientTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClientTest.java new file mode 100644 index 000000000..eb5dd121e --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/LongtaitouBalanceClientTest.java @@ -0,0 +1,180 @@ +package com.nanri.aiimage.modules.usersecret.client; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nanri.aiimage.config.UserSecretProperties; +import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * 龙抬头余额的口径判据(B83:密钥设置与后台列表显示人民币余额)。 + * + *

这一格要守的是「两套口径里挑了哪一套」。上游同一份响应给了美元串(顶层 + * {@code balance="$12.345678"})和 ⚡=人民币({@code credits.balance=88.888882}), + * 取错那一套不会报错、不会返空,只会安静地显示一个差 7.2 倍的数字——用户拿去对账单才发现。 + * 所以除了正向断言,这里还反向钉住「美元数字一个都不许出现在返回体里」。

+ */ +class LongtaitouBalanceClientTest { + + /** 官方文档 2026-10-19 那份 {@code GET /v1/skills/balance} 的响应样例,逐字照抄。 */ + private static final String OFFICIAL_SAMPLE = """ + { + "balance": "$12.345678", + "frozen": "$0.500000", + "available_balance": "$11.845678", + "currency": "USD", + "unit": "USD", + "credits": { + "balance": 88.888882, + "frozen": 3.6, + "available": 85.288882, + "unit": "CREDIT", + "per_usd": 7.2 + } + } + """; + + private final UserSecretProperties properties = new UserSecretProperties(); + private final LongtaitouBalanceClient client = + new LongtaitouBalanceClient(properties, new ObjectMapper()); + + @Test + void 人民币余额只取credits块不取顶层美元串() { + UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, OFFICIAL_SAMPLE); + + assertThat(vo.getAvailable()).isTrue(); + assertThat(vo.getBalance()).isEqualTo("88.888882"); + assertThat(vo.getAvailableBalance()).isEqualTo("85.288882"); + assertThat(vo.getFrozen()).isEqualTo("3.6"); + assertThat(vo.getUnit()).isEqualTo("CREDIT"); + assertThat(vo.getCheckedAt()).isNotNull(); + } + + @Test + void 美元数字一个都不许进返回体() { + UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, OFFICIAL_SAMPLE); + + // 界面上的 ¥ 后面挂上美元数=差 7.2 倍的假读数;这里把三个美元值全钉成「不许出现」 + assertThat(vo.getBalance()).doesNotContain("$").doesNotContain("12.34"); + assertThat(vo.getAvailableBalance()).doesNotContain("$").doesNotContain("11.84"); + assertThat(vo.getFrozen()).doesNotContain("$").doesNotContain("0.50"); + } + + @Test + void credits块缺失时宁可不显示也不回落美元() { + String onlyUsd = """ + {"balance": "$12.345678", "available_balance": "$11.845678", "currency": "USD"} + """; + + UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, onlyUsd); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getBalance()).isNull(); + assertThat(vo.getAvailableBalance()).isNull(); + assertThat(vo.getMessage()).as("说清为什么不给数字,而不是留一格空白让人以为是 0") + .contains("人民币").contains("不给金额"); + } + + @Test + void per_usd不为正时按口径不合格处理() { + String badPerUsd = """ + {"credits": {"balance": 88.888882, "available": 85.288882, "unit": "CREDIT", "per_usd": 0}} + """; + + assertThat(client.parseResponse(newVo(), 200, badPerUsd).getAvailable()).isFalse(); + } + + @Test + void credits单位不是CREDIT时不认这套口径() { + String otherUnit = """ + {"credits": {"balance": 88.888882, "available": 85.288882, "unit": "POINT", "per_usd": 7.2}} + """; + + UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, otherUnit); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getUnit()).isNull(); + } + + @Test + void credits缺available时不半显示() { + String half = """ + {"credits": {"balance": 88.888882, "unit": "CREDIT", "per_usd": 7.2}} + """; + + assertThat(client.parseResponse(newVo(), 200, half).getAvailable()).isFalse(); + } + + @Test + void 上游拒绝时原样带出原因且不抛异常() { + String denied = """ + {"error": {"code": "insufficient_permissions", "message": "该密钥没有账务权限", "type": "auth"}} + """; + + UserLlmBalanceVo vo = client.parseResponse(newVo(), 403, denied); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).contains("该密钥没有账务权限").contains("insufficient_permissions"); + assertThat(vo.getBalance()).isNull(); + } + + /** + * 现网实测形状(2026-11-05 从主机 B 直打 {@code longtaitou.token6688.com},不带任何真密钥): + * 无 Authorization ⇒ 401 {@code missing_api_key};带假 key ⇒ 401 {@code invalid_api_key}; + * 路径写错才是 404 {@code unknown_url}。这条格把"URL 派生对不对"与"被拒时说什么话"一起钉在实测读数上, + * 而不是钉在猜的错误体上——同一把尺子的 ④⑤ 两支若与这里冲突,以现网为准。 + */ + @Test + void 现网实测的401形状按查不到处理并把上游原话带出来() { + String missing = """ + {"error":{"code":"401","message":"Authorization header with Bearer token is required","type":"missing_api_key"}} + """; + String invalid = """ + {"error":{"code":"401","message":"Invalid API Key","type":"invalid_api_key"}} + """; + + assertThat(client.parseResponse(newVo(), 401, missing).getMessage()) + .contains("Authorization header with Bearer token is required").contains("401"); + UserLlmBalanceVo vo = client.parseResponse(newVo(), 401, invalid); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).contains("Invalid API Key"); + assertThat(vo.getBalance()).isNull(); + } + + @Test + void 非JSON应答按查不到处理() { + UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, "网关错误"); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).contains("JSON"); + } + + @Test + void 余额地址按渠道主机派生配置项只作覆盖() { + assertThat(client.balanceUrl()) + .isEqualTo(LlmChannel.LONGTAITOU.host() + "/v1/skills/balance"); + + properties.setLongtaitouBalanceUrl("https://mirror.example.com/v1/skills/balance"); + assertThat(client.balanceUrl()).isEqualTo("https://mirror.example.com/v1/skills/balance"); + } + + @Test + void 没有密钥时不调上游直接说未配置() { + assertThat(client.fetch(null).getAvailable()).isFalse(); + UserLlmBalanceVo vo = client.fetch(" "); + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).contains("未配置"); + // 上面两枚都必须在本方法里返回:真打了上游才会走到网络异常分支 + assertThat(vo.getChannel()).isEqualTo(LlmChannel.LONGTAITOU.key()); + } + + private static UserLlmBalanceVo newVo() { + UserLlmBalanceVo vo = new UserLlmBalanceVo(); + vo.setChannel(LlmChannel.LONGTAITOU.key()); + vo.setChannelLabel(LlmChannel.LONGTAITOU.label()); + return vo; + } +} diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceServiceTest.java new file mode 100644 index 000000000..1eae3c93e --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserLlmBalanceServiceTest.java @@ -0,0 +1,189 @@ +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * LLM 余额服务的分档、缓存与「三态不许伪装成 0」判据(B83)。 + * + *

形状照 {@link UserProxyBalanceServiceTest}:mock 协作者服务、不连库, + * 拒绝分支一律 {@code verifyNoInteractions} 钉住「一次上游都不打」。

+ */ +class UserLlmBalanceServiceTest { + + private static final long USER_ID = 7L; + private static final String AP = UserSecretModule.APPEARANCE_PATENT.key(); + private static final String SA = UserSecretModule.SIMILAR_ASIN.key(); + + private UserApiSecretService userApiSecretService; + private LongtaitouBalanceClient balanceClient; + private UserLlmBalanceService service; + + @BeforeEach + void setUp() { + userApiSecretService = mock(UserApiSecretService.class); + balanceClient = mock(LongtaitouBalanceClient.class); + service = new UserLlmBalanceService(userApiSecretService, balanceClient); + } + + @Test + void 贞贞渠道不打龙抬头接口也不借它的数字() { + when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.T8STAR.key()); + + UserLlmBalanceVo vo = service.balance(USER_ID, AP); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getBalance()).as("查不了就说查不了,一格空白或 0 都会被读成「没钱了」").isNull(); + assertThat(vo.getMessage()).contains(LlmChannel.T8STAR.label()).contains("不提供余额查询"); + verifyNoInteractions(balanceClient); + } + + @Test + void 渠道读的是任务执行同一个源不另解析一次() { + when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.LONGTAITOU.key()); + when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn("sk-ap"); + when(balanceClient.fetch("sk-ap")).thenReturn(fetched("88.888882", "85.288882")); + + UserLlmBalanceVo vo = service.balance(USER_ID, AP); + + assertThat(vo.getChannel()).isEqualTo(LlmChannel.LONGTAITOU.key()); + assertThat(vo.getModuleKey()).isEqualTo(AP); + assertThat(vo.getModuleLabel()).isEqualTo(UserSecretModule.APPEARANCE_PATENT.label()); + assertThat(vo.getBalance()).isEqualTo("88.888882"); + verify(userApiSecretService).findChannel(USER_ID, AP); + } + + @Test + void 龙抬头渠道但没存密钥时说未配置而不是零() { + when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.LONGTAITOU.key()); + when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn(""); + + UserLlmBalanceVo vo = service.balance(USER_ID, AP); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).contains("还没配置"); + assertThat(vo.getBalance()).isNull(); + verifyNoInteractions(balanceClient); + } + + @Test + void 五分钟缓存内不重复打上游() { + stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882"); + + service.balance(USER_ID, AP); + service.balance(USER_ID, AP); + + verify(balanceClient, times(1)).fetch("sk-ap"); + } + + @Test + void 改密钥后按userId整批失效下一次重打上游() { + stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882"); + stubLongtaitou(SA, "sk-sa", "10.5", "9.5"); + service.balance(USER_ID, AP); + service.balance(USER_ID, SA); + + service.invalidate(USER_ID); + service.balance(USER_ID, AP); + service.balance(USER_ID, SA); + + verify(balanceClient, times(2)).fetch("sk-ap"); + verify(balanceClient, times(2)).fetch("sk-sa"); + } + + @Test + void 失效只影响该用户不动别人的缓存() { + stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882"); + service.balance(USER_ID, AP); + service.invalidate(99L); + service.balance(USER_ID, AP); + + verify(balanceClient, times(1)).fetch("sk-ap"); + } + + @Test + void 两张卡各回各的钱A的数字不许出现在B行() { + stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882"); + stubLongtaitou(SA, "sk-sa", "12.500000", "10.000000"); + + List items = service.bundle(USER_ID); + + assertThat(items).hasSize(UserSecretModule.requiredModules().size()); + assertThat(items).extracting(UserLlmBalanceVo::getModuleKey).containsExactly(AP, SA); + assertThat(itemOf(items, AP).getBalance()).isEqualTo("88.888882"); + assertThat(itemOf(items, SA).getBalance()).isEqualTo("12.500000"); + assertThat(itemOf(items, SA).getBalance()).doesNotContain("88.88"); + } + + @Test + void 代理模块问LLM余额当场拒而不是回一格假数() { + assertThatThrownBy(() -> service.balance(USER_ID, UserSecretModule.PROXY.key())) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("代理"); + } + + @Test + void 未知模块与非法用户ID直接拒() { + assertThatThrownBy(() -> service.balance(USER_ID, "zhuan利汇")) + .isInstanceOf(BusinessException.class); + assertThatThrownBy(() -> service.balance(null, AP)).isInstanceOf(BusinessException.class); + assertThatThrownBy(() -> service.balance(0L, AP)).isInstanceOf(BusinessException.class); + verify(balanceClient, never()).fetch(any()); + } + + @Test + void 上游降级时服务不二次包装直接透传() { + UserLlmBalanceVo degraded = new UserLlmBalanceVo(); + degraded.setAvailable(false); + degraded.setMessage("龙抬头没有返回人民币(⚡)口径的余额块,为避免把美元数字当人民币显示,这里不给金额"); + when(userApiSecretService.findChannel(anyLong(), eq(AP))).thenReturn(LlmChannel.LONGTAITOU.key()); + when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn("sk-ap"); + when(balanceClient.fetch("sk-ap")).thenReturn(degraded); + + UserLlmBalanceVo vo = service.balance(USER_ID, AP); + + assertThat(vo.getAvailable()).isFalse(); + assertThat(vo.getMessage()).isEqualTo(degraded.getMessage()); + assertThat(vo.getModuleKey()).isEqualTo(AP); + } + + private void stubLongtaitou(String moduleKey, String plain, String balance, String available) { + when(userApiSecretService.findChannel(USER_ID, moduleKey)).thenReturn(LlmChannel.LONGTAITOU.key()); + when(userApiSecretService.findPlainValue(USER_ID, moduleKey)).thenReturn(plain); + when(balanceClient.fetch(plain)).thenReturn(fetched(balance, available)); + } + + private static UserLlmBalanceVo fetched(String balance, String available) { + UserLlmBalanceVo vo = new UserLlmBalanceVo(); + vo.setChannel(LlmChannel.LONGTAITOU.key()); + vo.setChannelLabel(LlmChannel.LONGTAITOU.label()); + vo.setAvailable(true); + vo.setBalance(balance); + vo.setAvailableBalance(available); + vo.setUnit("CREDIT"); + return vo; + } + + private static UserLlmBalanceVo itemOf(List items, String moduleKey) { + return items.stream().filter(item -> moduleKey.equals(item.getModuleKey())).findFirst().orElseThrow(); + } +} diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminServiceTest.java new file mode 100644 index 000000000..29f96944a --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserSecretBalanceAdminServiceTest.java @@ -0,0 +1,195 @@ +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * 后台余额侧写的三条护栏判据(B83:用户拍板「实时查上游、不落库」)。 + * + *

实时这条路的风险不是「查不到」,而是拿后管翻页去压上游和把超时读成没钱。 + * 所以三格各钉一个方向:上限必须当场拒(静默截断会让管理员以为整页都刷过了)、 + * 越权 userId 必须剔掉并回传(前端给的列表不是安全边界)、 + * 超预算的行必须报「未应答」且 {@code balance} 为空(一格 0 就是欠费假警报)。

+ */ +class UserSecretBalanceAdminServiceTest { + + private static final long USER_A = 1L; + private static final long USER_B = 2L; + private static final String AP = UserSecretModule.APPEARANCE_PATENT.key(); + + private UserLlmBalanceService llmBalanceService; + private UserProxyBalanceService proxyBalanceService; + private DataReadScope dataReadScope; + private UserSecretProperties properties; + private UserSecretBalanceAdminService service; + private final AdminUserEntity operator = new AdminUserEntity(); + + @BeforeEach + void setUp() { + llmBalanceService = mock(UserLlmBalanceService.class); + proxyBalanceService = mock(UserProxyBalanceService.class); + dataReadScope = mock(DataReadScope.class); + properties = new UserSecretProperties(); + service = new UserSecretBalanceAdminService( + llmBalanceService, proxyBalanceService, dataReadScope, properties); + } + + @Test + void 超过单次上限当场拒而不是静默截断() { + List ids = new ArrayList<>(); + for (long i = 1; i <= UserSecretBalanceAdminService.MAX_ROWS_PER_CALL + 1; i++) { + ids.add(i); + } + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered()); + + assertThatThrownBy(() -> service.balances(operator, query(ids))) + .isInstanceOf(BusinessException.class) + .hasMessageContaining(String.valueOf(UserSecretBalanceAdminService.MAX_ROWS_PER_CALL)) + .hasMessageContaining("每页数量"); + verifyNoInteractions(llmBalanceService, proxyBalanceService); + } + + @Test + void 越权userId不查并如实回传denied() { + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.users(List.of(USER_A))); + stubFast(USER_A); + + AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A, USER_B))); + + assertThat(vo.getItems()).extracting(AdminUserSecretBalancesVo.Item::getUserId) + .containsExactly(USER_A); + assertThat(vo.getDeniedUserIds()).containsExactly(USER_B); + verify(llmBalanceService, never()).balance(eq(USER_B), any()); + verify(proxyBalanceService, never()).balance(USER_B); + } + + @Test + void 超预算的行报未应答且余额为空() { + properties.setAdminBalanceDeadlineMillis(1000L); + properties.setAdminBalanceConcurrency(4); + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered()); + when(llmBalanceService.balance(anyLong(), any())).thenAnswer(invocation -> { + Thread.sleep(4000L); + return llm("88.888882"); + }); + when(proxyBalanceService.balance(USER_A)).thenAnswer(invocation -> { + Thread.sleep(4000L); + return proxy("1234"); + }); + + AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A))); + + AdminUserSecretBalancesVo.Item item = vo.getItems().get(0); + assertThat(item.getLlm()).hasSize(UserSecretModule.requiredModules().size()); + UserLlmBalanceVo llmRow = item.getLlm().get(0); + assertThat(llmRow.getAvailable()).isFalse(); + assertThat(llmRow.getBalance()).as("超时绝不是 0:一格 0 会被读成「欠费了」").isNull(); + assertThat(llmRow.getMessage()).contains("时间预算").contains("不代表余额为 0"); + assertThat(item.getProxy().getAvailable()).isFalse(); + assertThat(item.getProxy().getBalance()).isNull(); + assertThat(item.getProxy().getSurplus()).isNull(); + assertThat(vo.getTimedOutUserIds()).containsExactly(USER_A); + } + + @Test + void 正常行逐格带上数与代理侧写() { + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered()); + stubFast(USER_A); + + AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A))); + + AdminUserSecretBalancesVo.Item item = vo.getItems().get(0); + assertThat(item.getLlm()).extracting(UserLlmBalanceVo::getBalance) + .containsOnly("88.888882"); + assertThat(item.getProxy().getAvailable()).isTrue(); + assertThat(item.getProxy().getSurplus()).isEqualTo("1234"); + assertThat(vo.getTimedOutUserIds()).isEmpty(); + assertThat(vo.getDeniedUserIds()).isEmpty(); + } + + @Test + void 空请求与脏id不打上游() { + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered()); + + assertThat(service.balances(operator, query(List.of())).getItems()).isEmpty(); + // List.of 不吃 null,这里必须用 Arrays.asList 才造得出「前端塞了脏 id」那一形状 + assertThat(service.balances(operator, query(Arrays.asList(0L, -3L, null))).getItems()).isEmpty(); + assertThat(service.balances(operator, new AdminUserSecretBalanceQuery()).getItems()).isEmpty(); + verifyNoInteractions(llmBalanceService, proxyBalanceService); + } + + @Test + void 重复的userId去重后只查一轮() { + when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered()); + stubFast(USER_A); + + AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A, USER_A, USER_A))); + + assertThat(vo.getItems()).hasSize(1); + // 三行重复 id 若没去重,这里会变成 6 次 LLM + 3 次代理=拿后管页自己造洪水 + verify(llmBalanceService, times(UserSecretModule.requiredModules().size())) + .balance(eq(USER_A), any()); + verify(proxyBalanceService, times(1)).balance(USER_A); + } + + @Test + void 代填或清空后两族缓存一起丢() { + service.invalidate(USER_A); + + verify(llmBalanceService).invalidate(USER_A); + verify(proxyBalanceService).invalidate(USER_A); + } + + private void stubFast(long userId) { + when(llmBalanceService.balance(eq(userId), any())).thenReturn(llm("88.888882")); + when(proxyBalanceService.balance(userId)).thenReturn(proxy("1234")); + } + + private static UserLlmBalanceVo llm(String balance) { + UserLlmBalanceVo vo = new UserLlmBalanceVo(); + vo.setAvailable(true); + vo.setBalance(balance); + vo.setUnit("CREDIT"); + return vo; + } + + private static UserApiSecretBalanceVo proxy(String surplus) { + UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo(); + vo.setAvailable(true); + vo.setSurplus(surplus); + vo.setScope("user"); + return vo; + } + + private static AdminUserSecretBalanceQuery query(List userIds) { + AdminUserSecretBalanceQuery query = new AdminUserSecretBalanceQuery(); + query.setUserIds(userIds); + return query; + } +}