feat: 用量归属支持 callerRef 透传

- POST /ai/tasks 接受顶层可选 callerRef(限 64 字符),不进入 params、不参与幂等键、不进 prompt
- 结算时写进用量记录,lpt-be 据此做用户维度报表
- 复用已有任务时沿用原归属:那次 LLM 调用只发生一次,账算在原调用方头上
This commit is contained in:
2026-10-10 20:08:51 +08:00
parent 935f4781a4
commit 4aff5c03fe
9 changed files with 240 additions and 2 deletions
+22 -1
View File
@@ -10,6 +10,14 @@ import { safeFetchText, UnsafeUrlError } from "../utils/ssrf-guard.js";
import { RateLimiter, intFromEnv } from "../utils/rate-limit.js";
import { checkToken } from "../utils/auth.js";
/**
* 归属标记的最大长度。
*
* 它会落进日志与 lpt-be 的 `ai_usage_records.user_id`(VARCHAR(255)),
* 在入口限长比让数据库截断更安全。
*/
const MAX_CALLER_REF_LENGTH = 64;
export async function aiRoutes(app: FastifyInstance): Promise<void> {
const config = loadConfig();
@@ -52,9 +60,11 @@ export async function aiRoutes(app: FastifyInstance): Promise<void> {
idempotencyKey?: string;
/** 可选:跳过结果复用,强制重新生成 */
force?: boolean;
/** 可选:归属标记(lpt-be 传用户 id),原样写进用量记录;不参与幂等键 */
callerRef?: string;
};
}>("/ai/tasks", async (request, reply) => {
const { type, params, idempotencyKey, force } = request.body ?? {};
const { type, params, idempotencyKey, force, callerRef } = request.body ?? {};
const decision = taskLimiter.check(clientKey(request));
if (!decision.allowed) {
@@ -71,12 +81,23 @@ export async function aiRoutes(app: FastifyInstance): Promise<void> {
if (!params || typeof params !== "object") {
return reply.status(400).send({ error: "params 必须为非空对象" });
}
// 归属标记是 opaque 字符串,但必须限长:它会落进日志与数据库列(VARCHAR(64))
if (callerRef !== undefined && callerRef !== null) {
if (typeof callerRef !== "string" || callerRef.length > MAX_CALLER_REF_LENGTH) {
return reply
.status(400)
.send({ error: `callerRef 必须是不超过 ${MAX_CALLER_REF_LENGTH} 字符的字符串` });
}
}
const created = createTask(type as TaskType, params as Record<string, unknown>, {
...(typeof idempotencyKey === "string" && idempotencyKey.trim().length > 0
? { idempotencyKey }
: {}),
...(force === true ? { force: true } : {}),
...(typeof callerRef === "string" && callerRef.trim().length > 0
? { callerRef: callerRef.trim() }
: {}),
});
// 固定返回 201:Java 端 AiServiceClient 把非 201 当作提交失败,