feat: 用量归属支持 callerRef 透传
- POST /ai/tasks 接受顶层可选 callerRef(限 64 字符),不进入 params、不参与幂等键、不进 prompt - 结算时写进用量记录,lpt-be 据此做用户维度报表 - 复用已有任务时沿用原归属:那次 LLM 调用只发生一次,账算在原调用方头上
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import Fastify from "fastify";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { aiRoutes } from "./ai.js";
|
||||
import { getTask } from "../task-queue.js";
|
||||
|
||||
const originalDataDir = process.env.LPT_AI_DATA_DIR;
|
||||
const originalKey = process.env.LLM_API_KEY;
|
||||
const originalRateLimit = process.env.LPT_AI_RATE_LIMIT;
|
||||
let workDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// 面板日志会落盘,必须指向临时目录,否则会清掉开发者真实的面板数据
|
||||
workDir = mkdtempSync(join(tmpdir(), "lpt-ai-routes-"));
|
||||
process.env.LPT_AI_DATA_DIR = workDir;
|
||||
// 不配 Key:任务会以「LLM 不可用」快速失败,用例不需要真调 LLM
|
||||
delete process.env.LLM_API_KEY;
|
||||
process.env.LPT_AI_RATE_LIMIT = "10000";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [key, value] of [
|
||||
["LPT_AI_DATA_DIR", originalDataDir],
|
||||
["LLM_API_KEY", originalKey],
|
||||
["LPT_AI_RATE_LIMIT", originalRateLimit],
|
||||
] as const) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
rmSync(workDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function buildApp() {
|
||||
const app = Fastify();
|
||||
await app.register(aiRoutes);
|
||||
await app.ready();
|
||||
return app;
|
||||
}
|
||||
|
||||
function submit(app: Awaited<ReturnType<typeof buildApp>>, body: unknown) {
|
||||
return app.inject({
|
||||
method: "POST",
|
||||
url: "/ai/tasks",
|
||||
payload: body as Record<string, unknown>,
|
||||
});
|
||||
}
|
||||
|
||||
describe("POST /ai/tasks 的 callerRef(用量归属)", () => {
|
||||
it("带归属提交时落到任务记录上,供结算写进用量记录", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, {
|
||||
type: "guidance",
|
||||
params: { taskName: "t", concept: "c", history: [] },
|
||||
callerRef: "U-123",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const { taskId } = JSON.parse(response.body) as { taskId: string };
|
||||
expect(getTask(taskId)?.callerRef).toBe("U-123");
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("不传归属时任务记录上没有该字段", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, {
|
||||
type: "guidance",
|
||||
params: { taskName: "t", concept: "c", history: [] },
|
||||
});
|
||||
|
||||
const { taskId } = JSON.parse(response.body) as { taskId: string };
|
||||
expect(getTask(taskId)?.callerRef).toBeUndefined();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("空白归属视为未传,不写空字符串", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, {
|
||||
type: "guidance",
|
||||
params: { taskName: "t", concept: "c", history: [] },
|
||||
callerRef: " ",
|
||||
});
|
||||
|
||||
const { taskId } = JSON.parse(response.body) as { taskId: string };
|
||||
expect(getTask(taskId)?.callerRef).toBeUndefined();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("超过 64 字符被拒:它会落进日志与数据库列,限长比让库截断安全", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, {
|
||||
type: "guidance",
|
||||
params: { taskName: "t", concept: "c", history: [] },
|
||||
callerRef: "x".repeat(65),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(JSON.parse(response.body).error).toContain("64");
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("非字符串被拒,避免把对象写进归属列", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, {
|
||||
type: "guidance",
|
||||
params: { taskName: "t", concept: "c", history: [] },
|
||||
callerRef: { userId: "U-1" },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("归属不影响参数校验:type 非法仍然优先报错", async () => {
|
||||
const app = await buildApp();
|
||||
const response = await submit(app, { type: "nope", params: {}, callerRef: "U-1" });
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(JSON.parse(response.body).error).toContain("无效的 type");
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
+22
-1
@@ -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 当作提交失败,
|
||||
|
||||
Reference in New Issue
Block a user