feat(用户密钥): 龙抬头余额按人民币口径上界面——credits 查询+用户端/后管两个读取面
上游事实(官方文档+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 发版。
This commit is contained in:
+244
@@ -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}。
|
||||
*
|
||||
* <p><b>只认 {@code credits} 块</b>。上游同一份响应里给了两套口径:顶层
|
||||
* {@code balance / frozen / available_balance} 是<b>美元</b>串(形如 {@code "$12.345678"},
|
||||
* 带 {@code $} 前缀、6 位小数),{@code credits} 才是站内展示的 ⚡=<b>人民币</b>口径
|
||||
* (⚡=美元 × {@code credits.per_usd})。要跟用户看到的网页/账单对上必须用 {@code credits};
|
||||
* 而 {@code credits} 缺失时<b>不许</b>退回顶层美元串——把 {@code $12.34} 显示成 {@code ¥12.34}
|
||||
* 是「数字看着正常、含义是错的」那一类错,比一句「查不到」难发现得多。</p>
|
||||
*
|
||||
* <p>因此这里<b>不做任何汇率换算</b>(代码里出现汇率字面量就等于自己造了一套口径),
|
||||
* 也只把 {@code credits} 的值放进 VO——美元数字根本不进返回体,前端拿不到,也就没法误用。</p>
|
||||
*
|
||||
* <p>失败一律降级成 {@code available=false} 并原样带上原因,绝不抛出中断调用方(与
|
||||
* {@link JikipProxyClient} 同形)。</p>
|
||||
*/
|
||||
@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} 块取人民币口径;拿不到就是拿不到,<b>不回落美元</b>。
|
||||
*
|
||||
* <p>容许 {@code credits.frozen} 缺失(进行中任务没有预冻结时上游可能省略),但
|
||||
* {@code balance} 与 {@code available} 缺任一都不算成功——只有一半的余额数字更容易被读成「另一部分是 0」。</p>
|
||||
*/
|
||||
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) {
|
||||
}
|
||||
}
|
||||
+20
-2
@@ -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<AdminUserSecretBalancesVo> balances(
|
||||
HttpServletRequest request,
|
||||
@RequestBody AdminUserSecretBalanceQuery body) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
|
||||
return ApiResponse.success(userSecretBalanceAdminService.balances(operator, body));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{userId}")
|
||||
@Operation(summary = "清空该用户全部密钥与代理配置")
|
||||
public ApiResponse<Integer> 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}")
|
||||
|
||||
+28
-1
@@ -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<List<UserLlmBalanceVo>> 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<UserProxyPlanVo> proxyPlan(HttpServletRequest request) {
|
||||
|
||||
+23
@@ -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<Long> userIds;
|
||||
|
||||
/** 公司 tab 走 snake_case,与这一页的请求侧既有写法同形({@code company_id} 被尺子钉着)。 */
|
||||
@JsonProperty("company_id")
|
||||
@Schema(description = "公司 tab(只收窄、不放大;非超管一律按会话裁剪)")
|
||||
private Long companyId;
|
||||
}
|
||||
+41
@@ -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、零上游调用)。
|
||||
*
|
||||
* <p>这里的数是**取数时刻的快照**({@code UserLlmBalanceVo.checkedAt} 带在每格里),不是库里的列:
|
||||
* 后台不落余额快照,是为了不在每行加一次跨用户循环写、也不让界面读到几小时前的陈值。</p>
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "后台密钥管理-按用户回传的余额")
|
||||
public class AdminUserSecretBalancesVo {
|
||||
|
||||
@Schema(description = "逐用户的余额(顺序不保证与请求一致,前端按 userId 对号)")
|
||||
private List<Item> items;
|
||||
|
||||
@Schema(description = "被数据权限剔出、本次没有查的用户 ID(不静默少给数)")
|
||||
private List<Long> deniedUserIds;
|
||||
|
||||
@Schema(description = "因超出整请求时间预算而没有取到数的用户 ID")
|
||||
private List<Long> timedOutUserIds;
|
||||
|
||||
/** 一行的余额:两把 LLM 卡各有各的钱,代理余量另算一档。 */
|
||||
@Data
|
||||
@Schema(description = "单用户余额侧写")
|
||||
public static class Item {
|
||||
|
||||
@Schema(description = "用户 ID")
|
||||
private Long userId;
|
||||
|
||||
@Schema(description = "LLM 余额(外观专利/货源查询各一条,人民币口径)")
|
||||
private List<UserLlmBalanceVo> llm;
|
||||
|
||||
@Schema(description = "代理余量(jikip 套餐口径;青果为 scope=none,平台池为 scope=platform)")
|
||||
private UserApiSecretBalanceVo proxy;
|
||||
}
|
||||
}
|
||||
+53
@@ -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 渠道余额(龙抬头)。
|
||||
*
|
||||
* <p>刻意与 {@link UserApiSecretBalanceVo} 分开:那一个的 {@code surplus / scope / low} 全是
|
||||
* jikip 代理套餐的语义({@code surplus}=套餐剩余 IP <b>次数</b>、{@code scope}=user/platform),
|
||||
* 把 LLM 的人民币余额塞进去,等于让同一个字段名在两处表示两种东西——铁律 25 说的「口径不得借」
|
||||
* 防的正是这个(青果曾在这里显示成别人家的 jikip 余量)。</p>
|
||||
*/
|
||||
@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 = "总余额,<b>人民币(⚡)口径</b>的上游原样小数串(未取整,界面负责显示精度);"
|
||||
+ "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;
|
||||
}
|
||||
+137
@@ -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 卡与后台密钥管理列表共用这一处取数。
|
||||
*
|
||||
* <p>与 {@link UserProxyBalanceService} 分开成类,两条理由都记在这儿:① 缓存键不同
|
||||
* (这里是 {@code (userId, moduleKey)}——同一账号两把 LLM 密钥各有各的余额;那边是 {@code userId}
|
||||
* 单键,因为一个用户只有一套代理套餐);② 铁律 25「余量口径不得借」——两套语义装进一个类,
|
||||
* 注释迟早撒谎,而下一个人会照着撒谎的注释加分支。</p>
|
||||
*
|
||||
* <p><b>为什么渠道判据读 {@code findChannel} 而不是另解析一次</b>:这一列值就是任务执行时
|
||||
* 真正发请求用的那个渠道({@code UserApiSecretService#resolveLlmHost} 取的是同一个源)。
|
||||
* 闸门与展示各读各的会出现「界面说龙抬头、任务其实发贞贞」,所以铁律 27(a) 要求同源。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class UserLlmBalanceService {
|
||||
|
||||
/** 上游自己约 5 秒缓存同一把密钥的余额;这里再叠一层,是为了让后台列表翻页不逐页打上游。 */
|
||||
private static final long CACHE_MILLIS = 5 * 60 * 1000L;
|
||||
|
||||
/** key={@code userId|moduleKey};改/清/切渠道时按 userId 整批失效。 */
|
||||
private final Map<String, CachedLlmBalance> 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<UserLlmBalanceVo> bundle(Long userId) {
|
||||
List<UserLlmBalanceVo> 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 贞贞档的余额答复:不打上游、不借龙抬头的数。
|
||||
*
|
||||
* <p>贞贞有没有可用的余额端点<b>在册无判据</b>(龙抬头那份文档讲的是它自己家)。照青果那一档
|
||||
* 的先例({@code UserProxyBalanceService#qingguoUnsupported}):宁可说「查不了」,
|
||||
* 也不许猜一个端点、更不许把别家的钱挂在这一行上。</p>
|
||||
*/
|
||||
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<UserSecretModule> 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) {
|
||||
}
|
||||
}
|
||||
+225
@@ -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;
|
||||
|
||||
/**
|
||||
* 后台密钥管理列表的余额侧写:**实时打上游、不落库**。
|
||||
*
|
||||
* <p>列表本身({@code UserApiSecretService#adminPage})一次 {@code selectList} 组行,
|
||||
* 本类只在其后按本页用户补数,所以不引入任何新的 SQL 或 N+1 查库。</p>
|
||||
*
|
||||
* <p>三条护栏是这条路线的全部安全性(少一条,翻页就会变成打上游的洪水):</p>
|
||||
* <ol>
|
||||
* <li><b>单次调用上限</b> {@link #MAX_ROWS_PER_CALL} 个用户——超出直接拒,不做静默截断;</li>
|
||||
* <li><b>固定并发 + 整请求时间预算</b>:到点没回的行如实降级成 {@code available=false}
|
||||
* 并写明「上游未在预算内应答」,<b>绝不</b>降级成 0 或空表;</li>
|
||||
* <li><b>数据权限剔行</b>:请求里带的 userId 一律按 {@link DataReadScope} 收窄,
|
||||
* 越权的 id 不查、并回传在 {@code deniedUserIds} 里(不静默少给数)。
|
||||
* 前端给的 userId 列表<b>不是</b>安全边界。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>真正会发 HTTP 的行比请求行数少得多:非龙抬头渠道({@code UserLlmBalanceService})
|
||||
* 与青果供应商({@code UserProxyBalanceService})都在各自服务里直接判「不提供查询」,
|
||||
* 一次上游都不打;再加上两处 5 分钟内存缓存,翻页与反复点刷新不会逐次付费。</p>
|
||||
*/
|
||||
@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<Long> 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<Long> allowed = scope.userIdsOr(requested);
|
||||
List<Long> denied = new ArrayList<>(requested);
|
||||
denied.removeAll(allowed);
|
||||
|
||||
Map<Long, AdminUserSecretBalancesVo.Item> items = new ConcurrentHashMap<>();
|
||||
for (Long userId : allowed) {
|
||||
AdminUserSecretBalancesVo.Item item = new AdminUserSecretBalancesVo.Item();
|
||||
item.setUserId(userId);
|
||||
List<UserSecretModule> modules = UserSecretModule.requiredModules();
|
||||
List<UserLlmBalanceVo> 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<Long> 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<Pending> pendings = new ArrayList<>();
|
||||
try {
|
||||
for (Long userId : allowed) {
|
||||
List<UserSecretModule> 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<AdminUserSecretBalancesVo.Item> 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台代填/清空某用户配置后调用:两族余额缓存一起丢掉。
|
||||
*
|
||||
* <p>不这么做会出现「管理员刚换了钥匙,列表这一格还是上一把 key 的钱」——与用户端保存后
|
||||
* 必须失效是同一个串档形状,只是这里由本类统一收口({@code UserApiSecretService} 反向依赖
|
||||
* 余额服务会成环)。</p>
|
||||
*/
|
||||
public void invalidate(Long userId) {
|
||||
userLlmBalanceService.invalidate(userId);
|
||||
userProxyBalanceService.invalidate(userId);
|
||||
}
|
||||
|
||||
/** 等待单元:一个(用户 × 一个余额口径)。moduleKey 为 null 表示代理余量。 */
|
||||
private record Pending(Long userId, String moduleKey, Future<?> future,
|
||||
Consumer<Object> apply, Supplier<Object> 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<Long> distinct(List<Long> ids) {
|
||||
if (ids == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> out = new ArrayList<>();
|
||||
for (Long id : ids) {
|
||||
if (id != null && id > 0 && !out.contains(id)) {
|
||||
out.add(id);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user