feat: 用量统计支持用户维度报表

- 新增 ai_usage_records.user_id 与 (user_id, occurred_at) 索引,NULL 表示未归属
- 归属标记跟着请求走:AiServiceClient 提交任务时带上顶层 callerRef(当前用户 id),
  lpt-ai 原样透传,上报后落到 user_id。取不到身份就不带,绝不让 AI 调用因此失败
- breakdown 支持 groupBy=user,新增 label(登录名,未归属为「未归属」);
  summary/series/breakdown 支持 userId 过滤
This commit is contained in:
2026-10-10 20:28:04 +08:00
parent 650b0956de
commit 1ba3ae5a04
19 changed files with 619 additions and 45 deletions
@@ -5,14 +5,23 @@ import lombok.Data;
import java.math.BigDecimal;
/**
* 用量按任务类型 / 模型分组的一项(契约 2.4,{@code GET /ai/usage/breakdown})。
* 用量按任务类型 / 模型 / 用户分组的一项(契约 2.4、v2 第 4.2 节,{@code GET /ai/usage/breakdown})。
*/
@Data
public class AiUsageBreakdownItem {
/** 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名 */
/**
* 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名,
* {@code groupBy=user} 时是用户 id(未归属的记录为 null)。
*/
private String key;
/**
* 展示名:{@code groupBy=user} 时是登录名(未归属为「未归属」,查不到登录名时回退为 {@code key}),
* 其它分组维度下等于 {@code key}——前端统一渲染 {@code label} 即可,不必按维度分支。
*/
private String label;
private Long calls;
private Long successCalls;
@@ -20,9 +20,12 @@ public class AiUsageQuery {
/** 模型名,精确匹配;为空表示不限 */
private String model;
/** 归属用户 id,精确匹配;为空表示不限 */
private String userId;
/** series 的分桶粒度:day / hour */
private String bucket = "day";
/** breakdown 的分组维度:taskType / model */
/** breakdown 的分组维度:taskType / model / user */
private String groupBy = "taskType";
}
@@ -2,6 +2,7 @@ package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
@@ -28,6 +29,16 @@ public class AiUsageRecordRequest {
private String taskId;
/**
* 归属标记(契约 v2 第 2 节):lpt-be 提交任务时带的用户 id,lpt-ai 原样透传,落库到
* {@code ai_usage_records.user_id}。
*
* <p>刻意不用 {@code @NotBlank}:历史数据、lpt-ai 独立调用、以及调用方没带标记时都是空值,
* 空值只表示「未归属」,不是错误——用 {@code @NotBlank} 会把这类上报整批打成 400。</p>
*/
@Size(max = 64, message = "callerRef 不能超过 64 个字符")
private String callerRef;
/**
* 模型名。
*
@@ -42,6 +42,15 @@ public class AiUsageRecordEntity extends BaseEntity implements Serializable {
@TableField(value = "task_id")
private String taskId;
/**
* 归属用户:取自上报的 {@code callerRef};null=未归属(历史数据/独立调用/调用方没传)。
*
* <p>只用于分组与筛选,<strong>不是</strong>租户列:本表已在 {@code MybatisPlusConfig.EXCLUDE_TABLES}
* 中,绝不能按它过滤,否则面板只能看到当前管理员自己触发的调用。</p>
*/
@TableField(value = "user_id")
private String userId;
/** 模型名,如 deepseek-flash */
@TableField(value = "model")
private String model;
@@ -31,12 +31,14 @@ public interface AiUsageRecordMapper extends BaseMapper<AiUsageRecordEntity> {
* @param to 结束时刻(含);null 表示不限
* @param taskType 任务类型精确匹配;null 表示不限
* @param model 模型名精确匹配;null 表示不限
* @param userId 归属用户精确匹配;null 表示不限(契约 v2 第 4.1 节)
* @return 无匹配记录时返回全 0 的一行(AVG 为 null)
*/
AiUsageSummaryRow selectSummary(@Param("from") LocalDateTime from,
@Param("to") LocalDateTime to,
@Param("taskType") String taskType,
@Param("model") String model);
@Param("model") String model,
@Param("userId") String userId);
/**
* P95 调用耗时(毫秒,最近秩法:取第 {@code ceil(0.95 × 调用数)} 小的耗时)。
@@ -49,7 +51,8 @@ public interface AiUsageRecordMapper extends BaseMapper<AiUsageRecordEntity> {
Integer selectP95DurationMs(@Param("from") LocalDateTime from,
@Param("to") LocalDateTime to,
@Param("taskType") String taskType,
@Param("model") String model);
@Param("model") String model,
@Param("userId") String userId);
/**
* 按天或按小时分桶的用量趋势(契约 2.3)。
@@ -60,16 +63,18 @@ public interface AiUsageRecordMapper extends BaseMapper<AiUsageRecordEntity> {
@Param("to") LocalDateTime to,
@Param("taskType") String taskType,
@Param("model") String model,
@Param("userId") String userId,
@Param("bucket") String bucket);
/**
* 按任务类型或模型分组的用量(契约 2.4)。
* 按任务类型、模型或归属用户分组的用量(契约 2.4 / v2 第 4.2 节)。
*
* @param groupBy {@code taskType}(默认)或 {@code model}
* @param groupBy {@code taskType}(默认)、{@code model} 或 {@code user}
*/
List<AiUsageBreakdownRow> selectBreakdown(@Param("from") LocalDateTime from,
@Param("to") LocalDateTime to,
@Param("taskType") String taskType,
@Param("model") String model,
@Param("userId") String userId,
@Param("groupBy") String groupBy);
}
@@ -35,7 +35,7 @@ public interface AiUsageService {
/** 按天/按小时的用量趋势(契约 2.3) */
List<AiUsageSeriesPoint> series(AiUsageQuery query) throws ErrorParameterException;
/** 按任务类型/模型的用量分组(契约 2.4) */
/** 按任务类型/模型/归属用户的用量分组(契约 2.4、v2 第 4.2 节) */
List<AiUsageBreakdownItem> breakdown(AiUsageQuery query) throws ErrorParameterException;
/** 代理查询上游余额(契约 2.5);上游不可用时返回 {@code configured=false} */
@@ -4,6 +4,9 @@ import com.guo.learningprogresstracker.entity.UserEntity;
import com.baomidou.mybatisplus.extension.service.IService;
import com.guo.learningprogresstracker.exception.AppException;
import java.util.Collection;
import java.util.Map;
/**
* @author guo
* @description 针对表【user(用户信息表)】的数据库操作Service
@@ -28,4 +31,14 @@ public interface UserService extends IService<UserEntity> {
* @return 用户不存在时返回 null
*/
String getUserNameById(String userId);
/**
* 批量取登录名,用于「AI 用量统计」按用户分组的展示名(契约 v2 第 4.2 节)。
*
* <p>一次 {@code IN} 查询拿全部,避免每个分组各查一次(N+1)。</p>
*
* @param ids 用户 id 集合;为空或 null 时直接返回空 Map,不发查询
* @return 用户 id → 登录名;查不到的用户不会出现在结果里,由调用方决定回退文案
*/
Map<String, String> getUserNamesByIds(Collection<String> ids);
}
@@ -1,8 +1,11 @@
package com.guo.learningprogresstracker.service.impl;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.guo.learningprogresstracker.dto.ReportSections;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guo.learningprogresstracker.common.TenantContext;
import com.guo.learningprogresstracker.dto.ReportSections;
import jakarta.annotation.PostConstruct;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@@ -15,6 +18,7 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -213,7 +217,16 @@ public class AiServiceClient {
/** 提交任务到 lpt-ai /ai/tasks */
private String submitTask(String type, Map<String, Object> params) {
try {
Map<String, Object> body = Map.of("type", type, "params", params);
Map<String, Object> body = new LinkedHashMap<>();
body.put("type", type);
body.put("params", params);
// 归属标记(契约 v2 第 1 节):放在顶层,绝不放进 params——
// params 会喂给 prompt 模板、也参与 lpt-ai 的幂等键,混进去会污染两者。
// 拿不到身份时整个键都不写(等价于 null),这笔用量记为「未归属」。
String callerRef = currentCallerRef();
if (callerRef != null && !callerRef.isBlank()) {
body.put("callerRef", callerRef);
}
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url + "/ai/tasks"))
.timeout(Duration.ofSeconds(30)) // 提交本身不应超时
@@ -243,6 +256,32 @@ public class AiServiceClient {
}
}
/**
* 归属标记:当前执行身份的用户 id(契约 v2 第 1 节)。
*
* <p>口径与 {@code AutoTableField.currentLoginId()} 一致:后台执行线程通过
* {@link TenantContext} 显式声明身份,请求线程回落到 {@link StpUtil}。</p>
*
* <p>与自动填充不同的是这里<strong>必须容错</strong>:身份取不到只是这笔用量记成「未归属」,
* 不能让 AI 任务本身提交失败(非 Web 线程取 {@code StpUtil} 会抛
* {@code NotWebContextException},未登录时抛 {@code NotLoginException},两者都属
* {@link SaTokenException})。</p>
*
* @return 拿不到身份时返回 null,请求体里就不带 callerRef
*/
private static String currentCallerRef() {
TenantContext.Identity identity = TenantContext.get();
if (identity != null) {
return identity.loginId();
}
try {
return StpUtil.getLoginIdAsString();
} catch (SaTokenException e) {
log.debug("取不到当前身份,本次 AI 任务的用量将记为未归属: {}", e.getMessage());
return null;
}
}
/** 轮询等待任务完成 */
private Optional<JsonNode> pollResult(String taskId) {
Instant deadline = Instant.now().plusSeconds(timeoutSeconds);
@@ -6,6 +6,7 @@ import com.guo.learningprogresstracker.common.TenantContext;
import com.guo.learningprogresstracker.config.AiUsageProperties;
import com.guo.learningprogresstracker.dto.AiUsageBalance;
import com.guo.learningprogresstracker.dto.AiUsageBreakdownItem;
import com.guo.learningprogresstracker.dto.AiUsageBreakdownRow;
import com.guo.learningprogresstracker.dto.AiUsageIngestResult;
import com.guo.learningprogresstracker.dto.AiUsageSeriesPoint;
import com.guo.learningprogresstracker.dto.AiUsageSummary;
@@ -33,6 +34,8 @@ import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@@ -51,6 +54,10 @@ public class AiUsageServiceImpl implements AiUsageService {
private static final String BUCKET_HOUR = "hour";
private static final String GROUP_BY_TASK_TYPE = "taskType";
private static final String GROUP_BY_MODEL = "model";
private static final String GROUP_BY_USER = "user";
/** 未归属({@code user_id} 为 null)在面板上的展示名;契约 v2 第 4.2 节要求它单独可见 */
private static final String UNASSIGNED_LABEL = "未归属";
private final AiUsageRecordMapper aiUsageRecordMapper;
private final UserService userService;
@@ -126,6 +133,9 @@ public class AiUsageServiceImpl implements AiUsageService {
entity.setOccurredAt(parseUtc(record.getOccurredAt()));
entity.setTaskType(record.getTaskType());
entity.setTaskId(record.getTaskId());
// 归属标记原样落库:lpt-ai 不解释它的含义,这里也不校验它是否真是个存在的用户——
// 查不到用户名时面板回退显示用户 id(见 breakdown),比把整条用量丢掉强
entity.setUserId(record.getCallerRef());
entity.setModel(record.getModel());
entity.setAttempts(record.getAttempts());
entity.setIsLlmCall(record.getIsLlmCall());
@@ -175,9 +185,9 @@ public class AiUsageServiceImpl implements AiUsageService {
public AiUsageSummary summary(AiUsageQuery query) {
ResolvedFilter filter = resolve(query);
AiUsageSummaryRow row = aiUsageRecordMapper.selectSummary(
filter.from(), filter.to(), filter.taskType(), filter.model());
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId());
Integer p95DurationMs = aiUsageRecordMapper.selectP95DurationMs(
filter.from(), filter.to(), filter.taskType(), filter.model());
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId());
long cacheHitTokens = nullToZero(row.getCacheHitTokens());
long cacheMissTokens = nullToZero(row.getCacheMissTokens());
@@ -209,7 +219,7 @@ public class AiUsageServiceImpl implements AiUsageService {
String bucket = requireBucket(query == null ? null : query.getBucket());
return aiUsageRecordMapper.selectSeries(
filter.from(), filter.to(), filter.taskType(), filter.model(), bucket)
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), bucket)
.stream()
.map(row -> {
AiUsageSeriesPoint point = new AiUsageSeriesPoint();
@@ -230,26 +240,60 @@ public class AiUsageServiceImpl implements AiUsageService {
ResolvedFilter filter = resolve(query);
String groupBy = requireGroupBy(query == null ? null : query.getGroupBy());
return aiUsageRecordMapper.selectBreakdown(
filter.from(), filter.to(), filter.taskType(), filter.model(), groupBy)
.stream()
.map(row -> {
AiUsageBreakdownItem item = new AiUsageBreakdownItem();
item.setKey(row.getGroupKey());
item.setCalls(nullToZero(row.getCalls()));
item.setSuccessCalls(nullToZero(row.getSuccessCalls()));
item.setFailedCalls(nullToZero(row.getFailedCalls()));
item.setPromptTokens(nullToZero(row.getPromptTokens()));
item.setCompletionTokens(nullToZero(row.getCompletionTokens()));
item.setCacheHitTokens(nullToZero(row.getCacheHitTokens()));
item.setCostUsd(nullToZero(row.getCostUsd()));
item.setAvgDurationMs(row.getAvgDurationMs() == null
? null : Math.round(row.getAvgDurationMs()));
return item;
})
List<AiUsageBreakdownRow> rows = aiUsageRecordMapper.selectBreakdown(
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), groupBy);
// groupBy=user 的分组键是用户 id,前端要显示登录名;一次批量查完,不要按分组逐条查
Map<String, String> userNames = GROUP_BY_USER.equals(groupBy) ? loadUserNames(rows) : Map.of();
return rows.stream()
.map(row -> toBreakdownItem(row, groupBy, userNames))
.collect(Collectors.toList());
}
/** 分组键就是用户 id:去重后一次查完登录名(未归属的 null 键不参与查询) */
private Map<String, String> loadUserNames(List<AiUsageBreakdownRow> rows) {
Set<String> userIds = rows.stream()
.map(AiUsageBreakdownRow::getGroupKey)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
return userService.getUserNamesByIds(userIds);
}
private static AiUsageBreakdownItem toBreakdownItem(AiUsageBreakdownRow row, String groupBy,
Map<String, String> userNames) {
String key = row.getGroupKey();
AiUsageBreakdownItem item = new AiUsageBreakdownItem();
item.setKey(key);
item.setLabel(breakdownLabel(key, groupBy, userNames));
item.setCalls(nullToZero(row.getCalls()));
item.setSuccessCalls(nullToZero(row.getSuccessCalls()));
item.setFailedCalls(nullToZero(row.getFailedCalls()));
item.setPromptTokens(nullToZero(row.getPromptTokens()));
item.setCompletionTokens(nullToZero(row.getCompletionTokens()));
item.setCacheHitTokens(nullToZero(row.getCacheHitTokens()));
item.setCostUsd(nullToZero(row.getCostUsd()));
item.setAvgDurationMs(row.getAvgDurationMs() == null
? null : Math.round(row.getAvgDurationMs()));
return item;
}
/**
* 分组的展示名(契约 v2 第 4.2 节)。
*
* <p>非 user 分组下 label 就是 key:前端统一渲染 {@code label} 即可,不必按维度分支。
* user 分组下换成登录名;未归属(key 为 null)显示「未归属」,否则归属链路断了也看不出来;
* 查不到登录名时回退成用户 id,总比整行显示空白强。</p>
*/
private static String breakdownLabel(String key, String groupBy, Map<String, String> userNames) {
if (!GROUP_BY_USER.equals(groupBy)) {
return key;
}
if (key == null) {
return UNASSIGNED_LABEL;
}
return userNames.getOrDefault(key, key);
}
@Override
public AiUsageBalance balance() {
return aiUsageClient.fetchBalance();
@@ -268,7 +312,8 @@ public class AiUsageServiceImpl implements AiUsageService {
: LocalDateTime.ofInstant(Instant.ofEpochMilli(to), ZoneOffset.UTC);
return new ResolvedFilter(fromTime, toTime,
query == null ? null : query.getTaskType(),
query == null ? null : query.getModel());
query == null ? null : query.getModel(),
query == null ? null : query.getUserId());
}
private static String requireBucket(String bucket) throws ErrorParameterException {
@@ -287,8 +332,8 @@ public class AiUsageServiceImpl implements AiUsageService {
return GROUP_BY_TASK_TYPE;
}
String value = groupBy.trim();
if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value)) {
throw new ErrorParameterException("分组维度只支持 taskType 或 model");
if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value) && !GROUP_BY_USER.equals(value)) {
throw new ErrorParameterException("分组维度只支持 taskType、model 或 user");
}
return value;
}
@@ -302,6 +347,6 @@ public class AiUsageServiceImpl implements AiUsageService {
}
/** 解析后的查询条件(时间已转成 UTC 本地时间) */
private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model) {
private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model, String userId) {
}
}
@@ -10,6 +10,11 @@ import lombok.RequiredArgsConstructor;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author guo
* @description 针对表【user(用户信息表)】的数据库操作Service实现
@@ -42,4 +47,18 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity>
UserEntity userEntity = getById(userId);
return userEntity == null ? null : userEntity.getUserName();
}
@Override
public Map<String, String> getUserNamesByIds(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
// 只取 id 与 user_name 两列,避免把密码哈希这类字段拉出来
return list(Wrappers.<UserEntity>lambdaQuery()
.select(UserEntity::getId, UserEntity::getUserName)
.in(UserEntity::getId, ids))
.stream()
.collect(Collectors.toMap(UserEntity::getId, UserEntity::getUserName,
(first, second) -> first, LinkedHashMap::new));
}
}
@@ -0,0 +1,16 @@
-- 用户维度报表(契约 v2 第 3 节):用量记录归属到「哪个用户的任务消耗了这些 token」。
--
-- user_id 取自上报载荷的 callerRef:lpt-be 提交 AI 任务时把用户 id 作为归属标记带上,
-- lpt-ai 只做原样透传、不解释含义(它不知道调用方是谁),结算时写进用量记录。
-- 标记在 LLM 调用之前就已确定,因此没有「上报先到、归属还没写回」的竞态。
--
-- NULL = 未归属,来源有三种:改造前的历史数据、lpt-ai 独立调用、调用方没传 callerRef。
-- 面板必须能把「未归属」单独显示出来,否则归属链路断了也看不出来。
--
-- 注意:user_id **不是**租户列。本表已在 MybatisPlusConfig.EXCLUDE_TABLES 中,
-- 绝不能按 user_id 过滤(否则管理员只能看到自己触发的调用,面板等于永远是空的);
-- 它只用于分组与筛选,created_by 仍是审计列、不参与任何查询条件。
ALTER TABLE ai_usage_records ADD COLUMN user_id VARCHAR(255) NULL COMMENT '归属用户:取自上报的 callerRef;NULL=未归属(历史数据/独立调用/调用方没传)' AFTER error_code;
-- 按用户筛选或分组 + 时间范围。键长 utf8mb4 下 255×4 + 8 = 1028 字节,在 InnoDB 3072 上限内。
CREATE INDEX idx_ai_usage_records_user_occurred ON ai_usage_records (user_id, occurred_at);
@@ -48,6 +48,7 @@
面板口径:只看真正消耗 LLM 的调用(is_llm_call = 1),fetch-title 这类不消耗 LLM 的任务不进统计。
自定义 SQL 不会被 @TableLogic 自动追加逻辑删除条件,deleted = 0 必须显式写出;
而 created_by 条件刻意不写——本表是系统级表,用量要统计全部调用(见 MybatisPlusConfig)。
注意 user_id 不是租户列(同样不参与过滤),它只是归属标记:这里只按它做精确筛选与分组。
-->
<sql id="usageFilter">
WHERE deleted = 0
@@ -56,6 +57,7 @@
<if test="to != null">AND occurred_at &lt;= #{to}</if>
<if test="taskType != null and taskType != ''">AND task_type = #{taskType}</if>
<if test="model != null and model != ''">AND model = #{model}</if>
<if test="userId != null and userId != ''">AND user_id = #{userId}</if>
</sql>
<!--
@@ -124,6 +126,7 @@
SELECT
<choose>
<when test="groupBy == 'model'">model</when>
<when test="groupBy == 'user'">user_id</when>
<otherwise>task_type</otherwise>
</choose>
AS group_key,
@@ -140,6 +143,7 @@
GROUP BY
<choose>
<when test="groupBy == 'model'">model</when>
<when test="groupBy == 'user'">user_id</when>
<otherwise>task_type</otherwise>
</choose>
ORDER BY calls DESC, group_key
@@ -1,5 +1,7 @@
package com.guo.learningprogresstracker.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guo.learningprogresstracker.common.GlobalExceptionHandler;
import com.guo.learningprogresstracker.config.AiUsageProperties;
import com.guo.learningprogresstracker.dto.AiUsageIngestResult;
import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest;
@@ -9,19 +11,32 @@ import com.guo.learningprogresstracker.service.AiUsageService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* AiUsageInternalController 纯单元测试:令牌校验、单次条数上限、幂等结果透传。
* AiUsageInternalController 纯单元测试:令牌校验、单次条数上限、幂等结果透传,
* 以及归属标记 {@code callerRef} 的透传与长度约束(契约 v2 第 2 节)。
*
* <p>{@code @Size} 这类 Bean Validation 约束在直接调方法的单测里不会生效,
* 所以超长 callerRef 这条用例走 standalone MockMvc + {@link GlobalExceptionHandler},
* 看的是真实的 400 响应而不是注解本身。</p>
*/
@ExtendWith(MockitoExtension.class)
class AiUsageInternalControllerUnitTest {
@@ -116,6 +131,43 @@ class AiUsageInternalControllerUnitTest {
assertEquals(2, result.getData().getDuplicated());
}
/** 归属标记是可选的:历史数据与 lpt-ai 独立调用都没有它,带上时要能正常接收并透传给服务层 */
@Test
void report_withCallerRef_isAcceptedAndPassedThrough() throws Exception {
when(aiUsageService.ingest(any())).thenReturn(new AiUsageIngestResult(1, 0));
AiUsageReportRequest request = request(1);
request.getRecords().get(0).setCallerRef("U-123");
CommonResult<AiUsageIngestResult> result = controller.report("", request);
assertEquals(200, result.getCode());
assertEquals(1, result.getData().getAccepted());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<AiUsageRecordRequest>> captor = ArgumentCaptor.forClass(List.class);
verify(aiUsageService).ingest(captor.capture());
assertEquals("U-123", captor.getValue().get(0).getCallerRef());
}
/** 超过 64 字符的 callerRef 属于参数错误:400,且不落到服务层 */
@Test
void report_callerRefLongerThanSixtyFourCharacters_isRejected() throws Exception {
AiUsageReportRequest request = request(1);
request.getRecords().get(0).setCallerRef("x".repeat(65));
String body = new ObjectMapper().writeValueAsString(request);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new GlobalExceptionHandler())
.build();
mockMvc.perform(post("/internal/ai-usage/records")
.contentType(MediaType.APPLICATION_JSON)
.header("x-api-token", "")
.content(body))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(400));
verifyNoInteractions(aiUsageService);
}
private static AiUsageReportRequest request(int recordCount) {
List<AiUsageRecordRequest> records = new ArrayList<>(recordCount);
for (int i = 0; i < recordCount; i++) {
@@ -0,0 +1,104 @@
package com.guo.learningprogresstracker.service.impl;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaTokenContext;
import cn.dev33.satoken.context.SaTokenContextDefaultImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guo.learningprogresstracker.common.TenantContext;
import com.guo.learningprogresstracker.support.TestHttpServer;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* AiServiceClient 的用量归属标记测试(契约 v2 第 1 节)。
*
* <p>lpt-ai 不知道调用方是谁,因此 lpt-be 提交任务时必须把当前用户 id 作为顶层 {@code callerRef}
* 一起发过去,lpt-ai 结算时原样写进用量记录。这里守住三件事:</p>
* <ol>
* <li>标记确实等于当前执行身份(与 {@code AutoTableField.currentLoginId()} 同口径);</li>
* <li>标记放在顶层而<strong>不</strong>在 {@code params} 里——params 会喂给 prompt 模板、
* 也参与 lpt-ai 的幂等键,混进去会污染两者;</li>
* <li>取不到身份时任务照常提交(只是记成「未归属」):记账信息缺失不能让 AI 调用失败。</li>
* </ol>
*
* <p>用本地 {@link TestHttpServer} 承接 lpt-ai 的提交与轮询,不依赖真实网络。</p>
*/
class AiServiceClientAttributionTest extends TestHttpServer {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private AiServiceClient client() {
AiServiceClient client = new AiServiceClient();
client.setUrl(baseUrl());
client.init();
return client;
}
@Test
void aggregateReport_sendsCurrentIdentityAsCallerRef() {
stubSuccessfulTask();
TenantContext.callAs("U-123", null, () ->
client().aggregateReport("测试任务", List.of("碎片一"), null));
JsonNode body = submittedTaskBody();
assertEquals("aggregate-report", body.path("type").asText());
assertEquals("U-123", body.path("callerRef").asText(),
"归属标记必须是当前执行身份的用户 id,lpt-ai 靠它把用量记到具体用户头上");
}
@Test
void aggregateReport_keepsCallerRefOutOfParams() {
stubSuccessfulTask();
TenantContext.callAs("U-123", null, () ->
client().aggregateReport("测试任务", List.of("碎片一"), null));
JsonNode params = submittedTaskBody().path("params");
assertEquals("测试任务", params.path("taskName").asText(), "业务参数照常发过去");
assertFalse(params.has("callerRef"),
"callerRef 不能进 params:会污染 prompt 模板输入,也会改变 lpt-ai 的幂等键");
}
@Test
void aggregateReport_withoutIdentity_stillSubmitsWithoutCallerRef() {
stubSuccessfulTask();
// 既没有 TenantContext、也没有 Web 上下文:取身份会抛 SaTokenException,不能让它影响提交
SaTokenContext previous = SaManager.getSaTokenContext();
SaManager.setSaTokenContext(SaTokenContextDefaultImpl.defaultContext);
try {
client().aggregateReport("测试任务", List.of("碎片一"), null);
} finally {
SaManager.setSaTokenContext(previous);
}
JsonNode body = submittedTaskBody();
assertEquals("aggregate-report", body.path("type").asText(), "取不到身份不影响任务提交");
assertTrue(body.path("callerRef").isMissingNode() || body.path("callerRef").isNull(),
"取不到身份时记为「未归属」(不传或传 null),而不是编一个值");
}
/** 提交返回 taskId,随后轮询拿到一个非空结果 */
private void stubSuccessfulTask() {
route("POST", "/ai/tasks", 201, "{\"taskId\":\"task-1\"}");
route("GET", "/ai/tasks/task-1", 200,
"{\"status\":\"done\",\"result\":{\"sessionSummary\":\"这一段是总结\"}}");
}
private JsonNode submittedTaskBody() {
String body = requestBody("POST", "/ai/tasks");
assertTrue(body != null && !body.isBlank(), "lpt-ai 应当收到 POST /ai/tasks");
try {
return OBJECT_MAPPER.readTree(body);
} catch (Exception e) {
throw new AssertionError("提交请求体不是合法 JSON:" + body, e);
}
}
}
@@ -240,6 +240,7 @@ class AiUsageAggregationIntegrationTest {
assertEquals(10L, rowA.getCacheHitTokens());
assertEquals(0, new BigDecimal("0.006").compareTo(rowA.getCostUsd()));
assertEquals(2000L, rowA.getAvgDurationMs(), "(1000+3000+2000)/3");
assertEquals(taskTypeA, rowA.getLabel(), "非 user 分组下 label 等于 key,前端统一渲染 label 即可");
AiUsageBreakdownItem rowB = find(taskTypeRows, taskTypeB);
assertEquals(1L, rowB.getCalls());
@@ -260,6 +261,75 @@ class AiUsageAggregationIntegrationTest {
assertEquals(2667L, modelRowA.getAvgDurationMs(), "(1000+3000+4000)/3 四舍五入");
assertEquals(1L, find(modelRows, modelB).getCalls());
assertEquals(modelA, find(modelRows, modelA).getLabel(), "按模型分组时 label 同样是 key");
}
/**
* 契约 v2 第 4.2 节:按用户分组时展示名取 {@code user} 表里的登录名,
* 而 {@code user_id IS NULL} 的记录单独成一行、显示「未归属」——
* 否则归属链路断了也看不出来。
*/
@Test
void breakdown_groupByUser_labelsRowsWithUserNameAndUnassigned() throws Exception {
String taskType = unique("IT-BREAKDOWN-USER");
String from = "2026-05-05T00:00:00Z";
String to = "2026-05-06T00:00:00Z";
AiUsageRecordRequest attributed = breakdownRecord(taskType + "-1", taskType, "it-model-a",
"2026-05-05T09:00:00Z", 10, 5, "0.001", 1000, 200);
// 种子数据里 user id '1' 的登录名是 admin
attributed.setCallerRef("1");
// callerRef 留空 = 未归属(历史数据 / lpt-ai 独立调用 / 调用方没传)
AiUsageRecordRequest unassigned = breakdownRecord(taskType + "-2", taskType, "it-model-a",
"2026-05-05T09:10:00Z", 20, 5, "0.002", 2000, 200);
aiUsageService.ingest(List.of(attributed, unassigned));
AiUsageQuery query = query(from, to, taskType);
query.setGroupBy("user");
List<AiUsageBreakdownItem> rows = aiUsageService.breakdown(query);
assertEquals(2, rows.size());
AiUsageBreakdownItem attributedRow = find(rows, "1");
assertEquals(1L, attributedRow.getCalls());
assertEquals(10L, attributedRow.getPromptTokens());
assertEquals("admin", attributedRow.getLabel(), "展示名是 user 表里的登录名,不是用户 id");
AiUsageBreakdownItem unassignedRow = rows.stream()
.filter(row -> row.getKey() == null)
.findFirst()
.orElseThrow(() -> new AssertionError("未归属的记录应单独成一行,实际:" + rows));
assertEquals(1L, unassignedRow.getCalls());
assertEquals("未归属", unassignedRow.getLabel());
}
/** 契约 v2 第 4.1 节:userId 精确匹配,summary 与 series 都只统计该用户 */
@Test
void summaryAndSeries_filterByUserId() throws Exception {
String taskType = unique("IT-USER-FILTER");
String from = "2026-05-07T00:00:00Z";
String to = "2026-05-08T00:00:00Z";
AiUsageRecordRequest mine = record(taskType + "-1", taskType, "2026-05-07T09:00:00Z", true);
mine.setCallerRef("1");
mine.setPromptTokens(10);
AiUsageRecordRequest otherUser = record(taskType + "-2", taskType, "2026-05-07T09:10:00Z", true);
otherUser.setCallerRef("2");
otherUser.setPromptTokens(999);
AiUsageRecordRequest unassigned = record(taskType + "-3", taskType, "2026-05-07T09:20:00Z", true);
unassigned.setPromptTokens(555);
aiUsageService.ingest(List.of(mine, otherUser, unassigned));
AiUsageQuery query = query(from, to, taskType);
assertEquals(3L, aiUsageService.summary(query).getTotalCalls(), "不传 userId 时看全部调用");
query.setUserId("1");
AiUsageSummary filtered = aiUsageService.summary(query);
assertEquals(1L, filtered.getTotalCalls(), "只统计该用户的调用");
assertEquals(10L, filtered.getPromptTokens());
List<AiUsageSeriesPoint> points = aiUsageService.series(query);
assertEquals(1, points.size());
assertEquals(1L, points.get(0).getCalls());
}
@Test
@@ -9,27 +9,40 @@ import cn.dev33.satoken.servlet.model.SaResponseForServlet;
import cn.dev33.satoken.servlet.model.SaStorageForServlet;
import cn.dev33.satoken.stp.StpUtil;
import com.guo.learningprogresstracker.config.AiUsageProperties;
import com.guo.learningprogresstracker.dto.AiUsageBreakdownItem;
import com.guo.learningprogresstracker.dto.AiUsageBreakdownRow;
import com.guo.learningprogresstracker.dto.AiUsageSummary;
import com.guo.learningprogresstracker.dto.AiUsageSummaryRow;
import com.guo.learningprogresstracker.dto.request.AiUsageQuery;
import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest;
import com.guo.learningprogresstracker.entity.AiUsageRecordEntity;
import com.guo.learningprogresstracker.mapper.AiUsageRecordMapper;
import com.guo.learningprogresstracker.service.UserService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
@@ -118,8 +131,8 @@ class AiUsageServiceUnitTest {
@Test
void summary_cacheHitRateIsNullWhenDenominatorIsZero() {
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any())).thenReturn(row(3L, 0L, 0L));
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any())).thenReturn(null);
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any(), any())).thenReturn(row(3L, 0L, 0L));
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any(), any())).thenReturn(null);
AiUsageSummary summary = aiUsageService.summary(null);
@@ -135,8 +148,8 @@ class AiUsageServiceUnitTest {
AiUsageSummaryRow row = row(4L, 40L, 60L);
row.setCostUsd(new BigDecimal("0.01230000"));
row.setAvgDurationMs(7466.4);
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any())).thenReturn(row);
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any())).thenReturn(12000);
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any(), any())).thenReturn(row);
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any(), any())).thenReturn(12000);
AiUsageSummary summary = aiUsageService.summary(null);
@@ -156,8 +169,8 @@ class AiUsageServiceUnitTest {
AiUsageSummaryRow row = row(2L, 0L, 0L);
row.setPromptTokens(0L);
row.setUnreportedUsageCalls(1L);
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any())).thenReturn(row);
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any())).thenReturn(0);
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any(), any())).thenReturn(row);
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any(), any())).thenReturn(0);
AiUsageSummary summary = aiUsageService.summary(null);
@@ -166,6 +179,137 @@ class AiUsageServiceUnitTest {
assertEquals(0L, summary.getP95DurationMs());
}
/**
* 归属标记:上报的 {@code callerRef} 原样落到 {@code user_id},服务层不做任何解释或校验。
*
* <p>与租户无关:{@code user_id} 只是记账标记,本表不按它过滤(见 MybatisPlusConfig)。</p>
*/
@Test
void ingest_putsCallerRefIntoUserId() throws Exception {
AiUsageRecordRequest record = record();
record.setCallerRef("U-123");
aiUsageService.ingest(List.of(record));
ArgumentCaptor<AiUsageRecordEntity> captor = ArgumentCaptor.forClass(AiUsageRecordEntity.class);
verify(aiUsageRecordMapper).insert(captor.capture());
assertEquals("U-123", captor.getValue().getUserId());
}
/** 没有标记的上报(历史数据 / lpt-ai 独立调用)落成 null,即「未归属」,不能编一个值 */
@Test
void ingest_withoutCallerRef_leavesUserIdNull() throws Exception {
aiUsageService.ingest(List.of(record()));
ArgumentCaptor<AiUsageRecordEntity> captor = ArgumentCaptor.forClass(AiUsageRecordEntity.class);
verify(aiUsageRecordMapper).insert(captor.capture());
assertNull(captor.getValue().getUserId());
}
// ============ 用户维度 ============
@Test
void summary_passesUserIdFilterToMapper() {
when(aiUsageRecordMapper.selectSummary(any(), any(), any(), any(), eq("U-1")))
.thenReturn(row(1L, 0L, 0L));
when(aiUsageRecordMapper.selectP95DurationMs(any(), any(), any(), any(), eq("U-1"))).thenReturn(null);
AiUsageQuery query = new AiUsageQuery();
query.setUserId("U-1");
aiUsageService.summary(query);
verify(aiUsageRecordMapper).selectSummary(any(), any(), any(), any(), eq("U-1"));
verify(aiUsageRecordMapper).selectP95DurationMs(any(), any(), any(), any(), eq("U-1"));
}
/** groupBy=user 时展示名是登录名,未归属的行显示「未归属」而不是空白 */
@Test
void breakdown_groupByUser_labelsRowsWithUserNameOrUnassigned() throws Exception {
when(aiUsageRecordMapper.selectBreakdown(any(), any(), any(), any(), any(), eq("user")))
.thenReturn(List.of(breakdownRow("U-1", 3L), breakdownRow(null, 2L)));
when(userService.getUserNamesByIds(any())).thenReturn(Map.of("U-1", "cat"));
List<AiUsageBreakdownItem> items = aiUsageService.breakdown(queryGroupBy("user"));
assertEquals("U-1", items.get(0).getKey());
assertEquals("cat", items.get(0).getLabel());
assertNull(items.get(1).getKey());
assertEquals("未归属", items.get(1).getLabel(), "归属链路断了也要在面板上看得出来");
}
/** 用户名一次批量查完,且未归属(null 键)不参与查询——它不是用户 */
@Test
void breakdown_groupByUser_queriesUserNamesInOneBatchWithoutUnassignedKey() throws Exception {
when(aiUsageRecordMapper.selectBreakdown(any(), any(), any(), any(), any(), eq("user")))
.thenReturn(List.of(breakdownRow("U-1", 1L), breakdownRow("U-2", 1L), breakdownRow(null, 1L)));
when(userService.getUserNamesByIds(any())).thenReturn(Map.of("U-1", "cat", "U-2", "dog"));
aiUsageService.breakdown(queryGroupBy("user"));
@SuppressWarnings("unchecked")
ArgumentCaptor<Collection<String>> captor = ArgumentCaptor.forClass(Collection.class);
verify(userService).getUserNamesByIds(captor.capture());
assertEquals(Set.of("U-1", "U-2"), new HashSet<>(captor.getValue()));
}
/** 用户被删掉或 id 不对时回退成用户 id:总比整行显示空白强 */
@Test
void breakdown_groupByUser_unknownUser_fallsBackToKey() throws Exception {
when(aiUsageRecordMapper.selectBreakdown(any(), any(), any(), any(), any(), eq("user")))
.thenReturn(List.of(breakdownRow("ghost-id", 1L)));
when(userService.getUserNamesByIds(any())).thenReturn(Map.of());
List<AiUsageBreakdownItem> items = aiUsageService.breakdown(queryGroupBy("user"));
assertEquals("ghost-id", items.get(0).getLabel());
}
/** 其它分组维度下 label 等于 key:前端统一渲染 label 即可,不必按维度分支 */
@Test
void breakdown_taskType_labelEqualsKeyAndSkipsUserLookup() throws Exception {
when(aiUsageRecordMapper.selectBreakdown(any(), any(), any(), any(), any(), eq("taskType")))
.thenReturn(List.of(breakdownRow("aggregate-report", 1L)));
List<AiUsageBreakdownItem> items = aiUsageService.breakdown(queryGroupBy("taskType"));
assertEquals("aggregate-report", items.get(0).getKey());
assertEquals("aggregate-report", items.get(0).getLabel());
verifyNoInteractions(userService);
}
private static AiUsageQuery queryGroupBy(String groupBy) {
AiUsageQuery query = new AiUsageQuery();
query.setGroupBy(groupBy);
return query;
}
private static AiUsageBreakdownRow breakdownRow(String groupKey, long calls) {
AiUsageBreakdownRow row = new AiUsageBreakdownRow();
row.setGroupKey(groupKey);
row.setCalls(calls);
row.setSuccessCalls(calls);
row.setFailedCalls(0L);
row.setPromptTokens(0L);
row.setCompletionTokens(0L);
row.setCacheHitTokens(0L);
row.setCostUsd(BigDecimal.ZERO);
return row;
}
private static AiUsageRecordRequest record() {
AiUsageRecordRequest record = new AiUsageRecordRequest();
record.setRecordId("record-" + System.nanoTime());
record.setOccurredAt("2026-10-10T09:38:23.543Z");
record.setTaskType("aggregate-report");
record.setModel("deepseek-flash");
record.setAttempts(1);
record.setIsLlmCall(true);
record.setUsageSource("upstream");
record.setDurationMs(1000);
record.setStatus(200);
return record;
}
private static AiUsageSummaryRow row(long totalCalls, long cacheHitTokens, long cacheMissTokens) {
AiUsageSummaryRow row = new AiUsageSummaryRow();
row.setTotalCalls(totalCalls);
@@ -10,14 +10,18 @@ import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mindrot.jbcrypt.BCrypt;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* UserServiceImpl 单元测试:覆盖认证的用户不存在、密码错误、密码正确三条路径。
* UserServiceImpl 单元测试:覆盖认证的用户不存在、密码错误、密码正确三条路径,
* 以及「AI 用量统计」按用户分组用到的批量取登录名。
*/
@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
@@ -58,4 +62,15 @@ class UserServiceImplTest {
assertEquals("user-1", userService.authenticate("admin", "correct-pw"));
}
// ============ 批量取登录名(用量按用户分组的展示名) ============
/** 空集合直接返回空 Map:未归属的分组不构成查询条件,没必要为它跑一条 SQL */
@Test
void getUserNamesByIds_emptyIds_returnsEmptyMapWithoutQuery() {
assertTrue(userService.getUserNamesByIds(List.of()).isEmpty());
assertTrue(userService.getUserNamesByIds(null).isEmpty());
verify(userService, never()).list(any(Wrapper.class));
}
}
@@ -25,6 +25,8 @@ public class TestHttpServer {
private final List<Route> routes = new ArrayList<>();
/** 请求头按 "METHOD path" 记录(key 小写化),同名后续请求覆盖。 */
private final Map<String, Map<String, String>> requestHeadersByPath = new LinkedHashMap<>();
/** 请求体按 "METHOD path" 记录(UTF-8),同名后续请求覆盖;无请求体记为空串。 */
private final Map<String, String> requestBodiesByPath = new LinkedHashMap<>();
private final Map<String, String> lastPaths = new LinkedHashMap<>();
private final Map<String, String> lastQueries = new LinkedHashMap<>();
private String lastRequestKey;
@@ -43,14 +45,13 @@ public class TestHttpServer {
exchange.getRequestHeaders().forEach((k, v) -> lowercaseHeaders.put(k.toLowerCase(Locale.ROOT), String.join(",", v)));
lastRequestKey = method + " " + path;
requestHeadersByPath.put(lastRequestKey, lowercaseHeaders);
requestBodiesByPath.put(lastRequestKey,
new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
lastPaths.put(method + " " + path, path);
lastQueries.put(method + " " + path,
exchange.getRequestURI().getQuery() == null ? "" : exchange.getRequestURI().getQuery());
for (Route route : routes) {
if (route.method.equals(method) && path.startsWith(route.pathPrefix)) {
if (exchange.getRequestHeaders().getFirst("Content-Length") != null) {
exchange.getRequestBody().readAllBytes();
}
byte[] body = route.body();
Map<String, String> headers = new LinkedHashMap<>(route.headers());
boolean gzip = "gzip".equals(headers.remove("Content-Encoding-Test"));
@@ -121,4 +122,9 @@ public class TestHttpServer {
public String lastQuery(String method, String path) {
return lastQueries.get(method + " " + path);
}
/** 指定 "METHOD path" 的请求体(UTF-8);该路径尚未请求过返回 null,无请求体返回空串。 */
public String requestBody(String method, String path) {
return requestBodiesByPath.get(method + " " + path);
}
}