package com.guo.learningprogresstracker.controller; import com.guo.learningprogresstracker.config.AiUsageProperties; import com.guo.learningprogresstracker.dto.AiUsageIngestResult; import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest; import com.guo.learningprogresstracker.dto.request.AiUsageReportRequest; import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.service.AiUsageService; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * lpt-ai 用量上报(契约 1)。 * *

这是服务间接口,不是用户接口:调用方是 lpt-ai 进程,没有登录态, * 因此 {@code /internal/**} 已在 {@code WebMvcConfig} 中排除 Sa-Token 登录校验, * 改用 {@code x-api-token} 与 {@code lpt.ai-usage.report-token} 比对(配置为空表示不校验)。

*/ @RestController @RequestMapping("/internal/ai-usage") @RequiredArgsConstructor public class AiUsageInternalController { /** 契约 1:单次最多 200 条 */ static final int MAX_RECORDS_PER_REPORT = 200; private final AiUsageService aiUsageService; private final AiUsageProperties properties; /** * 上报用量记录。 * *

按 {@code recordId} 幂等:重复上报不报错,只在结果里体现为 {@code duplicated}。

*/ @PostMapping("/records") public CommonResult report( @RequestHeader(name = "x-api-token", required = false) String apiToken, @Valid @RequestBody AiUsageReportRequest request) throws ErrorParameterException { if (!isTokenAccepted(apiToken)) { return CommonResult.error("上报令牌不正确"); } List records = request.getRecords(); if (records.size() > MAX_RECORDS_PER_REPORT) { return CommonResult.error("单次最多上报 " + MAX_RECORDS_PER_REPORT + " 条记录"); } return CommonResult.success(aiUsageService.ingest(records)); } /** 契约 1:report-token 为空表示 lpt-ai 未启用令牌校验,直接放行 */ private boolean isTokenAccepted(String apiToken) { String expected = properties.getReportToken(); return expected == null || expected.isBlank() || expected.equals(apiToken); } }