/** 多组分流与历史配置解码;新方案不再包含默认组或固定B组比例。 */ import { z } from "zod"; import { experimentSchema, experimentGroupsSchema, type ContentInput, } from "./digital.schema"; /** 分组配置在保存和启动后保持稳定,返回值可为false、0或null。 */ export type ExperimentConfig = z.infer["config"] & { presetSnapshots?: Record; }; /** 单次实验中的组配置。 */ export type ExperimentGroup = ExperimentConfig["groups"][number]; /** 只读升级历史双组配置;保留旧哈希区间,不重分配已存在账号。 */ export function decodeExperimentConfig( raw: unknown, consumerKey?: string, ): ExperimentConfig { const c = raw as ExperimentConfig & { weightB?: number; baseline?: string; values?: Record; presetA?: string; presetB?: string; }; if (c.groups) return c; const value = (key: string): ExperimentGroup["value"] => c.values && Object.hasOwn(c.values, key) ? z.json().parse(c.values[key]) : consumerKey === "ui" ? key === "A" ? "old" : "new" : consumerKey === "chat" ? ((key === "A" ? c.presetA : c.presetB) ?? "") : null; const weightB = c.weightB ?? 5000; // 旧算法以B占据低位区间;保留这个顺序才能保证尚未落库的历史分组也稳定。 const groups = [ { key: "B", weight: weightB, value: value("B") }, { key: "A", weight: 10000 - weightB, value: value("A") }, ]; const { weightB: _weight, baseline: _baseline, values: _values, presetA: _a, presetB: _b, ...rest } = c; return { ...rest, groups: experimentGroupsSchema.parse(groups) }; } /** 半开区间覆盖全部流量;0%组从不命中自动分流。 */ export function groupAtBucket( groups: ExperimentGroup[], point: number, ): string { if (!Number.isInteger(point) || point < 0 || point >= 10000) throw new Error("分流位置须在0到9999之间"); let end = 0; for (const group of groups) { end += group.weight; if (point < end) return group.key; } throw new Error("分组比例未覆盖当前流量,请检查配置"); } /** 判断人工指定或保留结果引用的组是否仍属于本实验。 */ export function hasExperimentGroup(config: ExperimentConfig, key: string) { return config.groups.some((g) => g.key === key); }