mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-26 23:56:02 +08:00
e7badb1a24
* refactor(ui): simplify UpdateBadge to minimal dot indicator * feat(provider): add individual test and proxy config for providers Add support for provider-specific model test and proxy configurations: - Add ProviderTestConfig and ProviderProxyConfig types in Rust and TypeScript - Create ProviderAdvancedConfig component with collapsible panels - Update stream_check service to merge provider config with global config - Proxy config UI follows global proxy style (single URL input) Provider-level configs stored in meta field, no database schema changes needed. * feat(ui): add failover toggle and improve proxy controls - Add FailoverToggle component with slide animation - Simplify ProxyToggle style to match FailoverToggle - Add usage statistics button when proxy is active - Fix i18n parameter passing for failover messages - Add missing failover translation keys (inQueue, addQueue, priority) - Replace AboutSection icon with app logo * fix(proxy): support system proxy fallback and provider-level proxy config - Remove no_proxy() calls in http_client.rs to allow system proxy fallback - Add get_for_provider() to build HTTP client with provider-specific proxy - Update forwarder.rs and stream_check.rs to use provider proxy config - Fix EditProviderDialog.tsx to include provider.meta in useMemo deps - Add useEffect in ProviderAdvancedConfig.tsx to sync expand state Fixes #636 Fixes #583 * fix(ui): sync toast theme with app setting * feat(settings): add log config management Fixes #612 Fixes #514 * fix(proxy): increase request body size limit to 200MB Fixes #666 * docs(proxy): update timeout config descriptions and defaults Fixes #612 * fix(proxy): filter x-goog-api-key header to prevent duplication * fix(proxy): prevent proxy recursion when system proxy points to localhost Detect if HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY environment variables point to loopback addresses (localhost, 127.0.0.1), and bypass system proxy in such cases to avoid infinite request loops. * fix(i18n): add providerAdvanced i18n keys and fix failover toast parameter - Add providerAdvanced.* i18n keys to en.json, zh.json, and ja.json - Fix failover toggleFailed toast to pass detail parameter - Remove Chinese fallback text from UI for English/Japanese users * fix(tray): restore tray-provider events and enable Auto failover properly - Emit provider-switched event on tray provider click (backward compatibility) - Auto button now: starts proxy, takes over live config, enables failover * fix(log): enable dynamic log level and single file mode - Initialize log at Trace level for dynamic adjustment - Change rotation strategy to KeepSome(1) for single file - Set max file size to 1GB - Delete old log file on startup for clean start * fix(tray): fix clippy uninlined format args warning Use inline format arguments: {app_type_str} instead of {} * fix(provider): allow typing :// in endpoint URL inputs Change input type from "url" to "text" to prevent browser URL validation from blocking :// input. Closes #681 * fix(stream-check): use Gemini native streaming API format - Change endpoint from OpenAI-compatible to native streamGenerateContent - Add alt=sse parameter for SSE format response - Use x-goog-api-key header instead of Bearer token - Convert request body to Gemini contents/parts format * feat(proxy): add request logging for debugging Add debug logs for outgoing requests including URL and body content with byte size, matching the existing response logging format. * fix(log): prevent usize underflow in KeepSome rotation strategy KeepSome(n) internally computes n-2, so n=1 causes underflow. Use KeepSome(2) as the minimum safe value.
274 lines
7.4 KiB
TypeScript
274 lines
7.4 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||
import { failoverApi } from "@/lib/api/failover";
|
||
import { toast } from "sonner";
|
||
import { useTranslation } from "react-i18next";
|
||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||
|
||
// ========== 熔断器 Hooks ==========
|
||
|
||
/**
|
||
* 获取供应商健康状态
|
||
*/
|
||
export function useProviderHealth(providerId: string, appType: string) {
|
||
return useQuery({
|
||
queryKey: ["providerHealth", providerId, appType],
|
||
queryFn: () => failoverApi.getProviderHealth(providerId, appType),
|
||
enabled: !!providerId && !!appType,
|
||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||
retry: false,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 重置熔断器
|
||
*
|
||
* 重置后后端会检查是否应该切回优先级更高的供应商,
|
||
* 因此需要同时刷新供应商列表和代理状态。
|
||
*/
|
||
export function useResetCircuitBreaker() {
|
||
const queryClient = useQueryClient();
|
||
|
||
return useMutation({
|
||
mutationFn: ({
|
||
providerId,
|
||
appType,
|
||
}: {
|
||
providerId: string;
|
||
appType: string;
|
||
}) => failoverApi.resetCircuitBreaker(providerId, appType),
|
||
onSuccess: (_, variables) => {
|
||
// 刷新健康状态
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||
});
|
||
// 刷新供应商列表(因为可能发生了自动恢复切换)
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["providers", variables.appType],
|
||
});
|
||
// 刷新代理状态(更新 active_targets)
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["proxyStatus"],
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取熔断器配置
|
||
*/
|
||
export function useCircuitBreakerConfig() {
|
||
return useQuery({
|
||
queryKey: ["circuitBreakerConfig"],
|
||
queryFn: () => failoverApi.getCircuitBreakerConfig(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 更新熔断器配置
|
||
*/
|
||
export function useUpdateCircuitBreakerConfig() {
|
||
const queryClient = useQueryClient();
|
||
|
||
return useMutation({
|
||
mutationFn: failoverApi.updateCircuitBreakerConfig,
|
||
onSuccess: () => {
|
||
queryClient.invalidateQueries({ queryKey: ["circuitBreakerConfig"] });
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取熔断器统计信息
|
||
*/
|
||
export function useCircuitBreakerStats(providerId: string, appType: string) {
|
||
return useQuery({
|
||
queryKey: ["circuitBreakerStats", providerId, appType],
|
||
queryFn: () => failoverApi.getCircuitBreakerStats(providerId, appType),
|
||
enabled: !!providerId && !!appType,
|
||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||
});
|
||
}
|
||
|
||
// ========== 故障转移队列 Hooks(新) ==========
|
||
|
||
/**
|
||
* 获取故障转移队列
|
||
*/
|
||
export function useFailoverQueue(appType: string) {
|
||
return useQuery({
|
||
queryKey: ["failoverQueue", appType],
|
||
queryFn: () => failoverApi.getFailoverQueue(appType),
|
||
enabled: !!appType,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取可添加到队列的供应商
|
||
*/
|
||
export function useAvailableProvidersForFailover(appType: string) {
|
||
return useQuery({
|
||
queryKey: ["availableProvidersForFailover", appType],
|
||
queryFn: () => failoverApi.getAvailableProvidersForFailover(appType),
|
||
enabled: !!appType,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 添加供应商到故障转移队列
|
||
*/
|
||
export function useAddToFailoverQueue() {
|
||
const queryClient = useQueryClient();
|
||
|
||
return useMutation({
|
||
mutationFn: ({
|
||
appType,
|
||
providerId,
|
||
}: {
|
||
appType: string;
|
||
providerId: string;
|
||
}) => failoverApi.addToFailoverQueue(appType, providerId),
|
||
onSuccess: (_, variables) => {
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["failoverQueue", variables.appType],
|
||
});
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["availableProvidersForFailover", variables.appType],
|
||
});
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["providers", variables.appType],
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 从故障转移队列移除供应商
|
||
*/
|
||
export function useRemoveFromFailoverQueue() {
|
||
const queryClient = useQueryClient();
|
||
|
||
return useMutation({
|
||
mutationFn: ({
|
||
appType,
|
||
providerId,
|
||
}: {
|
||
appType: string;
|
||
providerId: string;
|
||
}) => failoverApi.removeFromFailoverQueue(appType, providerId),
|
||
onSuccess: (_, variables) => {
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["failoverQueue", variables.appType],
|
||
});
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["availableProvidersForFailover", variables.appType],
|
||
});
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["providers", variables.appType],
|
||
});
|
||
// 清除该供应商的健康状态缓存(退出队列后不再需要健康监控)
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||
});
|
||
// 清除该供应商的熔断器统计缓存
|
||
queryClient.invalidateQueries({
|
||
queryKey: [
|
||
"circuitBreakerStats",
|
||
variables.providerId,
|
||
variables.appType,
|
||
],
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
// ========== 自动故障转移开关 Hooks ==========
|
||
|
||
/**
|
||
* 获取指定应用的自动故障转移开关状态
|
||
*/
|
||
export function useAutoFailoverEnabled(appType: string) {
|
||
return useQuery({
|
||
queryKey: ["autoFailoverEnabled", appType],
|
||
queryFn: () => failoverApi.getAutoFailoverEnabled(appType),
|
||
// 默认值为 false(与后端保持一致)
|
||
placeholderData: false,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 设置指定应用的自动故障转移开关状态
|
||
*/
|
||
export function useSetAutoFailoverEnabled() {
|
||
const queryClient = useQueryClient();
|
||
const { t } = useTranslation();
|
||
|
||
return useMutation({
|
||
mutationFn: ({ appType, enabled }: { appType: string; enabled: boolean }) =>
|
||
failoverApi.setAutoFailoverEnabled(appType, enabled),
|
||
|
||
// 乐观更新
|
||
onMutate: async ({ appType, enabled }) => {
|
||
await queryClient.cancelQueries({
|
||
queryKey: ["autoFailoverEnabled", appType],
|
||
});
|
||
const previousValue = queryClient.getQueryData<boolean>([
|
||
"autoFailoverEnabled",
|
||
appType,
|
||
]);
|
||
|
||
queryClient.setQueryData(["autoFailoverEnabled", appType], enabled);
|
||
|
||
return { previousValue, appType };
|
||
},
|
||
|
||
onSuccess: (_data, variables) => {
|
||
const appLabel =
|
||
variables.appType === "claude"
|
||
? "Claude"
|
||
: variables.appType === "codex"
|
||
? "Codex"
|
||
: "Gemini";
|
||
|
||
toast.success(
|
||
variables.enabled
|
||
? t("failover.enabled", {
|
||
app: appLabel,
|
||
defaultValue: `${appLabel} 故障转移已启用`,
|
||
})
|
||
: t("failover.disabled", {
|
||
app: appLabel,
|
||
defaultValue: `${appLabel} 故障转移已关闭`,
|
||
}),
|
||
{ closeButton: true },
|
||
);
|
||
},
|
||
|
||
// 错误时回滚
|
||
onError: (error: Error, _variables, context) => {
|
||
if (context?.previousValue !== undefined) {
|
||
queryClient.setQueryData(
|
||
["autoFailoverEnabled", context.appType],
|
||
context.previousValue,
|
||
);
|
||
}
|
||
|
||
const detail =
|
||
extractErrorMessage(error) ||
|
||
t("common.unknown", { defaultValue: "未知错误" });
|
||
toast.error(
|
||
t("failover.toggleFailed", {
|
||
detail,
|
||
defaultValue: `操作失败: ${detail}`,
|
||
}),
|
||
);
|
||
},
|
||
|
||
// 无论成功失败,都重新获取
|
||
onSettled: (_, __, variables) => {
|
||
queryClient.invalidateQueries({
|
||
queryKey: ["autoFailoverEnabled", variables.appType],
|
||
});
|
||
},
|
||
});
|
||
}
|