Files
monkey-ai-web/src/pages/Setting/Operation/SettingsFallback.jsx
T

409 lines
16 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import { Button, Col, Form, Row, Spin, Banner } from '@/components/ui';
import {
compareObjects,
API,
isRoot,
showError,
showSuccess,
showWarning,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
export default function SettingsFallback(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({
// Phase 1
'fallback_setting.enabled': false,
'fallback_setting.max_depth': 3,
'fallback_setting.timeout_ms': 60000,
'fallback_setting.total_timeout_ms': 180000,
'fallback_setting.billing_mode': 'actual',
'fallback_setting.edit_permission': 'root_only',
// Phase 2
'fallback_setting.allow_cross_group': false,
'fallback_setting.cross_border_allowed': false,
'fallback_setting.bound_user_allowed': false,
// Phase 3
'fallback_setting.cooling_seconds': 30,
'fallback_setting.per_token_max_per_minute': 0,
'fallback_setting.rollout_percent': 100,
'fallback_setting.max_attempts_per_request': 10,
});
const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs);
function onSubmit() {
const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
// 前端先校验总超时 ≥ 单跳超时(单跳超时为 0 表示关闭,不校验);
// 后端只校验各自范围,不校验两者关系
const timeoutMs = Number(inputs['fallback_setting.timeout_ms']);
const totalTimeoutMs = Number(inputs['fallback_setting.total_timeout_ms']);
if (timeoutMs > 0 && totalTimeoutMs < timeoutMs) {
return showError(t('整条链总超时应不小于单跳超时'));
}
const requestQueue = updateArray.map((item) =>
API.put('/api/option/', {
key: item.key,
value: String(inputs[item.key]),
}),
);
setLoading(true);
// 逐个检查业务结果:后端校验失败返回 HTTP 200 + success:false,
// 只看 Promise 是否 resolve 会把失败误报为保存成功
Promise.allSettled(requestQueue)
.then((results) => {
const failedMessages = [];
results.forEach((r) => {
if (r.status === 'fulfilled' && r.value?.data?.success) return;
const message =
r.status === 'fulfilled'
? r.value?.data?.message
: r.reason?.response?.data?.message || r.reason?.message;
failedMessages.push(message || t('保存失败,请重试'));
});
if (failedMessages.length === 0) {
showSuccess(t('保存成功'));
} else {
showError(
t('保存失败: ') + Array.from(new Set(failedMessages)).join(';'),
);
}
})
.finally(() => {
setLoading(false);
// 无论成败都回读,让页面与库中实际值保持一致
props.refresh();
});
}
const onOptionsChange = useEffectEvent(() => {
const currentInputs = {};
for (let key in props.options) {
if (Object.keys(inputs).includes(key)) {
currentInputs[key] = props.options[key];
}
}
// 合并已有 inputs 默认值,避免覆盖丢失
const merged = { ...inputs, ...currentInputs };
setInputs(merged);
setInputsRow(structuredClone(merged));
refForm.current?.setValues(merged);
});
useEffect(() => onOptionsChange(), [onOptionsChange, props.options]);
return (
<Spin spinning={loading}>
<Form
values={inputs}
getFormApi={(formAPI) => (refForm.current = formAPI)}
style={{ marginBottom: 15 }}
>
<Form.Section text={t('兜底渠道设置(Fallback Channels)')}>
<Banner
type='info'
description={t(
'当主渠道请求失败时,按各渠道配置的兜底链顺序自动切换;用户侧无感。详见技术方案文档。',
)}
closeIcon={null}
style={{ marginBottom: 12 }}
/>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.enabled'}
label={t('兜底渠道总开关')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.enabled': value })
}
extraText={t('关闭后所有兜底逻辑跳过,行为与改造前一致')}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.max_depth'}
label={t('单次请求最大兜底链长(1-10)')}
min={1}
max={10}
precision={0}
onNumberChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.max_depth': value })
}
style={{ width: '100%' }}
/>
</Col>
{/* 计费策略/编辑权限属于策略键,后端下放黑名单保持 root-only;
对非 root 隐藏,避免"能看不能存"(保存必 403)的断裂 */}
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
field={'fallback_setting.billing_mode'}
label={t('兜底计费策略')}
optionList={[
{ value: 'actual', label: t('按实际渠道价(默认)') },
{
value: 'main_capped',
label: t('按主渠道价封顶(Phase 4 待实现)'),
disabled: true,
},
{
value: 'min',
label: t('取较低价(Phase 4 待实现)'),
disabled: true,
},
]}
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.billing_mode': value,
})
}
style={{ width: '100%' }}
extraText={t(
'Phase 1-3 仅实现 actual 策略;其他选项当前不生效',
)}
/>
</Col>
)}
</Row>
<Row gutter={16} style={{ marginTop: 12 }}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.timeout_ms'}
label={t('单跳超时(毫秒)')}
min={0}
max={1800000}
precision={0}
onNumberChange={(value) =>
setInputs({ ...inputs, 'fallback_setting.timeout_ms': value })
}
style={{ width: '100%' }}
extraText={t(
'0 = 关闭单跳超时;超时覆盖整个流式响应,长输出模型请调大或设为 0;图像生成链路的单跳超时最低 300 秒',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.total_timeout_ms'}
label={t('整条链总超时(毫秒)')}
min={5000}
max={1800000}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.total_timeout_ms': value,
})
}
style={{ width: '100%' }}
extraText={t('总超时后熔断返回 503;应不小于单跳超时')}
/>
</Col>
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Select
field={'fallback_setting.edit_permission'}
label={t('兜底配置编辑权限')}
optionList={[
{ value: 'root_only', label: t('仅 Root 管理员(推荐)') },
{
value: 'scope_check',
label: t('按可见范围校验(待实现)'),
disabled: true,
},
]}
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.edit_permission': value,
})
}
style={{ width: '100%' }}
/>
</Col>
)}
</Row>
</Form.Section>
<Form.Section text={t('兜底渠道-合规与边界(Phase 2)')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.allow_cross_group'}
label={t('允许跨分组兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.allow_cross_group': value,
})
}
extraText={t(
'关闭时仅允许同分组的渠道作为兜底;auto 分组按实际选中的分组判断;用户分组未知时自动跳过本限制',
)}
/>
</Col>
{/* 跨境兜底涉及数据出境合规,后端下放黑名单保持 root-only;
对非 root 隐藏,避免"能看不能存"(保存必失败)的断裂 */}
{isRoot() && (
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.cross_border_allowed'}
label={t('允许跨境兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.cross_border_allowed': value,
})
}
extraText={t(
'关闭时仅当源/目标都标记 Region 且不同时拦截;涉及数据出境合规',
)}
/>
</Col>
)}
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.Switch
field={'fallback_setting.bound_user_allowed'}
label={t('绑定用户渠道允许兜底')}
size='default'
checkedText='|'
uncheckedText='〇'
onChange={(value) =>
setInputs({
...inputs,
'fallback_setting.bound_user_allowed': value,
})
}
extraText={t(
'关闭时,被绑定到任一渠道的用户的所有请求都不走兜底;开启后这些用户的请求也会走兜底链',
)}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('兜底渠道-保护与放量(Phase 3)')}>
<Row gutter={16}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.cooling_seconds'}
label={t('失败渠道冷却秒数')}
min={0}
max={86400}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.cooling_seconds': value,
})
}
style={{ width: '100%' }}
extraText={t(
'兜底渠道刚失败后 N 秒内被跳过,同时作为重试耗尽标记的时长;0 = 禁用冷却与重试耗尽标记。需 Redis 启用',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.per_token_max_per_minute'}
label={t('单 token 每分钟兜底触发上限')}
min={0}
max={100000}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.per_token_max_per_minute': value,
})
}
style={{ width: '100%' }}
extraText={t(
'0 = 不限。超过上限的请求不再触发兜底。需 Redis 启用',
)}
/>
</Col>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.rollout_percent'}
label={t('灰度放量百分比(0-100)')}
min={0}
max={100}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.rollout_percent': value,
})
}
style={{ width: '100%' }}
extraText={t(
'按用户 ID 哈希决定该用户是否启用兜底;100=全部启用,0=全部关闭',
)}
/>
</Col>
</Row>
<Row gutter={16} style={{ marginTop: 12 }}>
<Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.InputNumber
field={'fallback_setting.max_attempts_per_request'}
label={t('单请求最大上游尝试次数(1-50)')}
min={1}
max={50}
precision={0}
onNumberChange={(value) =>
setInputs({
...inputs,
'fallback_setting.max_attempts_per_request': value,
})
}
style={{ width: '100%' }}
extraText={t(
'单个请求最多向上游发起的调用次数,包含同渠道重试和兜底切换,防止快速失败时调用次数失控;仅对配置了失败次数大于 1 的渠道生效',
)}
/>
</Col>
</Row>
</Form.Section>
<Row>
<Button size='default' onClick={onSubmit} style={{ marginTop: 8 }}>
{t('保存兜底渠道设置')}
</Button>
</Row>
</Form>
</Spin>
);
}