feat(experiments): 新增后台场景注册与应用接入映射

保留已有ui/chat场景与分组,支持命名、创建和停用;同一应用接入点实验互斥,保护历史场景类型与运行实验;增加自定义场景决策回归。
This commit is contained in:
湛兮
2026-10-27 11:01:52 +08:00
parent fd0b039729
commit 2e3a7c0a7e
7 changed files with 257 additions and 32 deletions
+85
View File
@@ -0,0 +1,85 @@
/** 场景注册与启停;场景映射到现有应用接入点,不执行任意代码。 */
import { z } from "zod";
import type { PoolConnection } from "mysql2/promise";
import { rows, write, audit, transaction } from "./digital.repository";
import { badRequest, conflict, notFound } from "../../shared/http-error";
/** 场景编辑契约,版本号保护并发编辑。 */
export const sceneSchema = z.object({
name: z.string().trim().min(1).max(120),
runtime: z.enum(["ui", "chat"]),
description: z.string().max(2000).default(""),
enabled: z.boolean().default(true),
revision: z.number().int().positive().optional(),
});
/** 后台场景记录。 */
export type Scene = {
id: string;
name: string;
runtime: "ui" | "chat";
description: string;
enabled: number;
builtin: number;
revision: number;
};
/** 已注册场景,包括停用场景以便解释历史实验。 */
export async function scenes() {
return rows<Scene>(
"SELECT * FROM dh_scenes ORDER BY builtin DESC,created_at,id",
);
}
/** 查询场景并在配置事务内锁定映射,避免修改执行类型与发布竞争。 */
export async function scene(id: string, c?: PoolConnection) {
const [s] = await rows<Scene>(
`SELECT * FROM dh_scenes WHERE id=?${c ? " FOR UPDATE" : ""}`,
[id],
c,
);
if (!s) throw notFound("实验场景不存在,请先创建场景");
return s;
}
/** 已使用场景不能切换接入点;运行/暂停中的场景不可停用。 */
export async function saveScene(
actor: string,
id: string,
input: z.infer<typeof sceneSchema>,
) {
await transaction(async (c) => {
await rows(
"SELECT version FROM schema_migrations ORDER BY version LIMIT 1 FOR UPDATE",
[],
c,
);
const [old] = await rows<Scene>(
"SELECT * FROM dh_scenes WHERE id=? FOR UPDATE",
[id],
c,
);
if (old && old.revision !== input.revision)
throw conflict("场景已更新,请刷新后重试");
const usage = await rows<{ state: string }>(
"SELECT state FROM dh_experiments WHERE scope=?",
[id],
c,
);
if (old && old.runtime !== input.runtime && (old.builtin || usage.length))
throw badRequest("系统预置或已用于实验的场景不能更换接入点");
if (
!input.enabled &&
usage.some((e) => e.state === "running" || e.state === "paused")
)
throw conflict("请先结束该场景的运行/暂停实验,再停用场景");
if (old)
await write(
"UPDATE dh_scenes SET name=?,runtime=?,description=?,enabled=?,revision=revision+1 WHERE id=?",
[input.name, input.runtime, input.description, input.enabled, id],
c,
);
else
await write(
"INSERT INTO dh_scenes(id,name,runtime,description,enabled) VALUES (?,?,?,?,?)",
[id, input.name, input.runtime, input.description, input.enabled],
c,
);
await audit(actor, old ? "scene.update" : "scene.create", id, input, c);
});
}