feat(experiments): 独立注册实验类型并分离用户分组查询

- 实验类型:自定义标识、数据契约、默认值和真实调用后的接入验收

- 测试方案:按类型校验 A/B 值,保留历史分组与预设快照,未验收禁止发布

- 用户管理:真实账号分页搜索、只读预览与有效账号人工指定校验

- 文档与验证:同步迁移014及消费者接口说明,15项核心回归通过
This commit is contained in:
湛兮
2026-10-27 11:40:02 +08:00
parent 7ba4241995
commit 094d0c17e8
10 changed files with 590 additions and 82 deletions
+9 -58
View File
@@ -1,8 +1,7 @@
/** 场景注册与启停;场景映射到现有应用接入点,不执行任意代码。 */
/** 历史场景只读兼容;新类型使用独立注册表。 */
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";
import { rows } from "./digital.repository";
import { badRequest } from "../../shared/http-error";
/** 场景编辑契约,版本号保护并发编辑。 */
export const sceneSchema = z.object({
name: z.string().trim().min(1).max(120),
@@ -24,62 +23,14 @@ export type Scene = {
/** 已注册场景,包括停用场景以便解释历史实验。 */
export async function scenes() {
return rows<Scene>(
"SELECT * FROM dh_scenes ORDER BY builtin DESC,created_at,id",
"SELECT * FROM dh_scenes WHERE runtime IS NOT NULL 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>,
_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);
});
throw badRequest("场景入口已升级,请刷新后台后使用「实验类型」创建入口");
}