mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-28 00:35:32 +08:00
fix(proxy): improve validation and error handling in proxy config panels
- Add StopTimeout/StopFailed error types for proper stop() error reporting - Replace silent clamp with validation-and-block in config panels - Add listenAddress format validation in ProxyPanel - Use log_codes constants instead of hardcoded strings - Use once_cell::Lazy for regex precompilation
This commit is contained in:
@@ -61,24 +61,121 @@ export function AutoFailoverConfigPanel({
|
||||
const n = parseInt(val);
|
||||
return isNaN(n) ? defaultVal : n;
|
||||
};
|
||||
|
||||
// 定义各字段的有效范围
|
||||
const ranges = {
|
||||
maxRetries: { min: 0, max: 10 },
|
||||
streamingFirstByteTimeout: { min: 0, max: 180 },
|
||||
streamingIdleTimeout: { min: 0, max: 600 },
|
||||
nonStreamingTimeout: { min: 0, max: 1800 },
|
||||
circuitFailureThreshold: { min: 1, max: 20 },
|
||||
circuitSuccessThreshold: { min: 1, max: 10 },
|
||||
circuitTimeoutSeconds: { min: 10, max: 300 },
|
||||
circuitErrorRateThreshold: { min: 0, max: 100 },
|
||||
circuitMinRequests: { min: 5, max: 100 },
|
||||
};
|
||||
|
||||
// 解析原始值
|
||||
const raw = {
|
||||
maxRetries: parseNum(formData.maxRetries, 3),
|
||||
streamingFirstByteTimeout: parseNum(
|
||||
formData.streamingFirstByteTimeout,
|
||||
30,
|
||||
),
|
||||
streamingIdleTimeout: parseNum(formData.streamingIdleTimeout, 60),
|
||||
nonStreamingTimeout: parseNum(formData.nonStreamingTimeout, 300),
|
||||
circuitFailureThreshold: parseNum(formData.circuitFailureThreshold, 5),
|
||||
circuitSuccessThreshold: parseNum(formData.circuitSuccessThreshold, 2),
|
||||
circuitTimeoutSeconds: parseNum(formData.circuitTimeoutSeconds, 60),
|
||||
circuitErrorRateThreshold: parseNum(
|
||||
formData.circuitErrorRateThreshold,
|
||||
50,
|
||||
),
|
||||
circuitMinRequests: parseNum(formData.circuitMinRequests, 10),
|
||||
};
|
||||
|
||||
// 校验是否超出范围
|
||||
const errors: string[] = [];
|
||||
const checkRange = (
|
||||
value: number,
|
||||
range: { min: number; max: number },
|
||||
label: string,
|
||||
) => {
|
||||
if (value < range.min || value > range.max) {
|
||||
errors.push(`${label}: ${range.min}-${range.max}`);
|
||||
}
|
||||
};
|
||||
|
||||
checkRange(
|
||||
raw.maxRetries,
|
||||
ranges.maxRetries,
|
||||
t("proxy.autoFailover.maxRetries", "最大重试次数"),
|
||||
);
|
||||
checkRange(
|
||||
raw.streamingFirstByteTimeout,
|
||||
ranges.streamingFirstByteTimeout,
|
||||
t("proxy.autoFailover.streamingFirstByte", "流式首字节超时"),
|
||||
);
|
||||
checkRange(
|
||||
raw.streamingIdleTimeout,
|
||||
ranges.streamingIdleTimeout,
|
||||
t("proxy.autoFailover.streamingIdle", "流式静默超时"),
|
||||
);
|
||||
checkRange(
|
||||
raw.nonStreamingTimeout,
|
||||
ranges.nonStreamingTimeout,
|
||||
t("proxy.autoFailover.nonStreaming", "非流式超时"),
|
||||
);
|
||||
checkRange(
|
||||
raw.circuitFailureThreshold,
|
||||
ranges.circuitFailureThreshold,
|
||||
t("proxy.autoFailover.failureThreshold", "失败阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.circuitSuccessThreshold,
|
||||
ranges.circuitSuccessThreshold,
|
||||
t("proxy.autoFailover.successThreshold", "恢复成功阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.circuitTimeoutSeconds,
|
||||
ranges.circuitTimeoutSeconds,
|
||||
t("proxy.autoFailover.timeout", "恢复等待时间"),
|
||||
);
|
||||
checkRange(
|
||||
raw.circuitErrorRateThreshold,
|
||||
ranges.circuitErrorRateThreshold,
|
||||
t("proxy.autoFailover.errorRate", "错误率阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.circuitMinRequests,
|
||||
ranges.circuitMinRequests,
|
||||
t("proxy.autoFailover.minRequests", "最小请求数"),
|
||||
);
|
||||
|
||||
if (errors.length > 0) {
|
||||
toast.error(
|
||||
t("proxy.autoFailover.validationFailed", {
|
||||
fields: errors.join("; "),
|
||||
defaultValue: `以下字段超出有效范围: ${errors.join("; ")}`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await updateConfig.mutateAsync({
|
||||
appType,
|
||||
enabled: config.enabled,
|
||||
autoFailoverEnabled: formData.autoFailoverEnabled,
|
||||
maxRetries: parseNum(formData.maxRetries, 3),
|
||||
streamingFirstByteTimeout: parseNum(
|
||||
formData.streamingFirstByteTimeout,
|
||||
30,
|
||||
),
|
||||
streamingIdleTimeout: parseNum(formData.streamingIdleTimeout, 60),
|
||||
nonStreamingTimeout: parseNum(formData.nonStreamingTimeout, 300),
|
||||
circuitFailureThreshold: parseNum(formData.circuitFailureThreshold, 5),
|
||||
circuitSuccessThreshold: parseNum(formData.circuitSuccessThreshold, 2),
|
||||
circuitTimeoutSeconds: parseNum(formData.circuitTimeoutSeconds, 60),
|
||||
circuitErrorRateThreshold:
|
||||
parseNum(formData.circuitErrorRateThreshold, 50) / 100,
|
||||
circuitMinRequests: parseNum(formData.circuitMinRequests, 10),
|
||||
maxRetries: raw.maxRetries,
|
||||
streamingFirstByteTimeout: raw.streamingFirstByteTimeout,
|
||||
streamingIdleTimeout: raw.streamingIdleTimeout,
|
||||
nonStreamingTimeout: raw.nonStreamingTimeout,
|
||||
circuitFailureThreshold: raw.circuitFailureThreshold,
|
||||
circuitSuccessThreshold: raw.circuitSuccessThreshold,
|
||||
circuitTimeoutSeconds: raw.circuitTimeoutSeconds,
|
||||
circuitErrorRateThreshold: raw.circuitErrorRateThreshold / 100,
|
||||
circuitMinRequests: raw.circuitMinRequests,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.autoFailover.configSaved", "自动故障转移配置已保存"),
|
||||
|
||||
@@ -7,12 +7,14 @@ import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState, useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/**
|
||||
* 熔断器配置面板
|
||||
* 允许用户调整熔断器参数
|
||||
*/
|
||||
export function CircuitBreakerConfigPanel() {
|
||||
const { t } = useTranslation();
|
||||
const { data: config, isLoading } = useCircuitBreakerConfig();
|
||||
const updateConfig = useUpdateCircuitBreakerConfig();
|
||||
|
||||
@@ -44,18 +46,88 @@ export function CircuitBreakerConfigPanel() {
|
||||
const n = parseInt(val);
|
||||
return isNaN(n) ? defaultVal : n;
|
||||
};
|
||||
|
||||
// 定义各字段的有效范围
|
||||
const ranges = {
|
||||
failureThreshold: { min: 1, max: 20 },
|
||||
successThreshold: { min: 1, max: 10 },
|
||||
timeoutSeconds: { min: 10, max: 300 },
|
||||
errorRateThreshold: { min: 0, max: 100 },
|
||||
minRequests: { min: 5, max: 100 },
|
||||
};
|
||||
|
||||
// 解析原始值
|
||||
const raw = {
|
||||
failureThreshold: parseNum(formData.failureThreshold, 5),
|
||||
successThreshold: parseNum(formData.successThreshold, 2),
|
||||
timeoutSeconds: parseNum(formData.timeoutSeconds, 60),
|
||||
errorRateThreshold: parseNum(formData.errorRateThreshold, 50),
|
||||
minRequests: parseNum(formData.minRequests, 10),
|
||||
};
|
||||
|
||||
// 校验是否超出范围
|
||||
const errors: string[] = [];
|
||||
const checkRange = (
|
||||
value: number,
|
||||
range: { min: number; max: number },
|
||||
label: string,
|
||||
) => {
|
||||
if (value < range.min || value > range.max) {
|
||||
errors.push(`${label}: ${range.min}-${range.max}`);
|
||||
}
|
||||
};
|
||||
|
||||
checkRange(
|
||||
raw.failureThreshold,
|
||||
ranges.failureThreshold,
|
||||
t("circuitBreaker.failureThreshold", "失败阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.successThreshold,
|
||||
ranges.successThreshold,
|
||||
t("circuitBreaker.successThreshold", "成功阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.timeoutSeconds,
|
||||
ranges.timeoutSeconds,
|
||||
t("circuitBreaker.timeoutSeconds", "超时时间"),
|
||||
);
|
||||
checkRange(
|
||||
raw.errorRateThreshold,
|
||||
ranges.errorRateThreshold,
|
||||
t("circuitBreaker.errorRateThreshold", "错误率阈值"),
|
||||
);
|
||||
checkRange(
|
||||
raw.minRequests,
|
||||
ranges.minRequests,
|
||||
t("circuitBreaker.minRequests", "最小请求数"),
|
||||
);
|
||||
|
||||
if (errors.length > 0) {
|
||||
toast.error(
|
||||
t("circuitBreaker.validationFailed", {
|
||||
fields: errors.join("; "),
|
||||
defaultValue: `以下字段超出有效范围: ${errors.join("; ")}`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = {
|
||||
failureThreshold: parseNum(formData.failureThreshold, 5),
|
||||
successThreshold: parseNum(formData.successThreshold, 2),
|
||||
timeoutSeconds: parseNum(formData.timeoutSeconds, 60),
|
||||
errorRateThreshold: parseNum(formData.errorRateThreshold, 50) / 100,
|
||||
minRequests: parseNum(formData.minRequests, 10),
|
||||
};
|
||||
await updateConfig.mutateAsync(parsed);
|
||||
toast.success("熔断器配置已保存", { closeButton: true });
|
||||
await updateConfig.mutateAsync({
|
||||
failureThreshold: raw.failureThreshold,
|
||||
successThreshold: raw.successThreshold,
|
||||
timeoutSeconds: raw.timeoutSeconds,
|
||||
errorRateThreshold: raw.errorRateThreshold / 100,
|
||||
minRequests: raw.minRequests,
|
||||
});
|
||||
toast.success(t("circuitBreaker.configSaved", "熔断器配置已保存"), {
|
||||
closeButton: true,
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error("保存失败: " + String(error));
|
||||
toast.error(
|
||||
t("circuitBreaker.saveFailed", "保存失败") + ": " + String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -102,13 +102,42 @@ export function ProxyPanel() {
|
||||
|
||||
const handleSaveBasicConfig = async () => {
|
||||
if (!globalConfig) return;
|
||||
|
||||
// 校验地址格式(简单的 IP 地址或 localhost 校验)
|
||||
const addressTrimmed = listenAddress.trim();
|
||||
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
const isValidAddress =
|
||||
addressTrimmed === "localhost" ||
|
||||
addressTrimmed === "0.0.0.0" ||
|
||||
(ipv4Regex.test(addressTrimmed) &&
|
||||
addressTrimmed.split(".").every((n) => {
|
||||
const num = parseInt(n);
|
||||
return num >= 0 && num <= 255;
|
||||
}));
|
||||
if (!isValidAddress) {
|
||||
toast.error(
|
||||
t("proxy.settings.invalidAddress", {
|
||||
defaultValue:
|
||||
"地址无效,请输入有效的 IP 地址(如 127.0.0.1)或 localhost",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const port = parseInt(listenPort);
|
||||
const validPort = isNaN(port) || port < 1024 || port > 65535 ? 15721 : port;
|
||||
if (isNaN(port) || port < 1024 || port > 65535) {
|
||||
toast.error(
|
||||
t("proxy.settings.invalidPort", {
|
||||
defaultValue: "端口无效,请输入 1024-65535 之间的数字",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateGlobalConfig.mutateAsync({
|
||||
...globalConfig,
|
||||
listenAddress,
|
||||
listenPort: validPort,
|
||||
listenAddress: addressTrimmed,
|
||||
listenPort: port,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.settings.configSaved", { defaultValue: "代理配置已保存" }),
|
||||
|
||||
@@ -1107,7 +1107,12 @@
|
||||
"toast": {
|
||||
"saved": "Proxy configuration saved",
|
||||
"saveFailed": "Save failed: {{error}}"
|
||||
}
|
||||
},
|
||||
"invalidPort": "Invalid port, please enter a number between 1024-65535",
|
||||
"invalidAddress": "Invalid address, please enter a valid IP address (e.g. 127.0.0.1) or localhost",
|
||||
"configSaved": "Proxy configuration saved",
|
||||
"configSaveFailed": "Failed to save configuration",
|
||||
"restartRequired": "Restart proxy service for address or port changes to take effect"
|
||||
},
|
||||
"switchFailed": "Switch failed: {{error}}",
|
||||
"failover": {
|
||||
@@ -1134,6 +1139,7 @@
|
||||
"info": "When the failover queue has multiple providers, the system will try them in priority order when requests fail. When a provider reaches the consecutive failure threshold, the circuit breaker will open and skip it temporarily.",
|
||||
"configSaved": "Auto failover config saved",
|
||||
"configSaveFailed": "Failed to save",
|
||||
"validationFailed": "The following fields are out of valid range: {{fields}}",
|
||||
"retrySettings": "Retry & Timeout Settings",
|
||||
"failureThreshold": "Failure Threshold",
|
||||
"failureThresholdHint": "Open circuit breaker after this many consecutive failures (recommended: 3-10)",
|
||||
@@ -1185,6 +1191,16 @@
|
||||
"streamingIdle": "Streaming Idle Timeout",
|
||||
"nonStreaming": "Non-Streaming Timeout"
|
||||
},
|
||||
"circuitBreaker": {
|
||||
"failureThreshold": "Failure Threshold",
|
||||
"successThreshold": "Success Threshold",
|
||||
"timeoutSeconds": "Timeout (seconds)",
|
||||
"errorRateThreshold": "Error Rate Threshold",
|
||||
"minRequests": "Min Requests",
|
||||
"validationFailed": "The following fields are out of valid range: {{fields}}",
|
||||
"configSaved": "Circuit breaker config saved",
|
||||
"saveFailed": "Failed to save"
|
||||
},
|
||||
"universalProvider": {
|
||||
"title": "Universal Provider",
|
||||
"description": "Universal providers manage Claude, Codex, and Gemini configurations simultaneously. Changes are automatically synced to all enabled apps.",
|
||||
|
||||
@@ -1107,7 +1107,12 @@
|
||||
"toast": {
|
||||
"saved": "代理配置已保存",
|
||||
"saveFailed": "保存失败: {{error}}"
|
||||
}
|
||||
},
|
||||
"invalidPort": "端口无效,请输入 1024-65535 之间的数字",
|
||||
"invalidAddress": "地址无效,请输入有效的 IP 地址(如 127.0.0.1)或 localhost",
|
||||
"configSaved": "代理配置已保存",
|
||||
"configSaveFailed": "保存配置失败",
|
||||
"restartRequired": "修改地址或端口后需要重启代理服务才能生效"
|
||||
},
|
||||
"switchFailed": "切换失败: {{error}}",
|
||||
"failover": {
|
||||
@@ -1134,6 +1139,7 @@
|
||||
"info": "当故障转移队列中配置了多个供应商时,系统会在请求失败时按优先级顺序依次尝试。当某个供应商连续失败达到阈值时,熔断器会打开并在一段时间内跳过该供应商。",
|
||||
"configSaved": "自动故障转移配置已保存",
|
||||
"configSaveFailed": "保存失败",
|
||||
"validationFailed": "以下字段超出有效范围: {{fields}}",
|
||||
"retrySettings": "重试与超时设置",
|
||||
"failureThreshold": "失败阈值",
|
||||
"failureThresholdHint": "连续失败多少次后打开熔断器(建议: 3-10)",
|
||||
@@ -1185,6 +1191,16 @@
|
||||
"streamingIdle": "流式静默超时",
|
||||
"nonStreaming": "非流式超时"
|
||||
},
|
||||
"circuitBreaker": {
|
||||
"failureThreshold": "失败阈值",
|
||||
"successThreshold": "成功阈值",
|
||||
"timeoutSeconds": "超时时间",
|
||||
"errorRateThreshold": "错误率阈值",
|
||||
"minRequests": "最小请求数",
|
||||
"validationFailed": "以下字段超出有效范围: {{fields}}",
|
||||
"configSaved": "熔断器配置已保存",
|
||||
"saveFailed": "保存失败"
|
||||
},
|
||||
"universalProvider": {
|
||||
"title": "统一供应商",
|
||||
"description": "统一供应商可以同时管理 Claude、Codex 和 Gemini 的配置。修改后会自动同步到所有启用的应用。",
|
||||
|
||||
Reference in New Issue
Block a user