refactor: clash-verge-service management (#4674)

* refactor: clash-verge-service management

* fix: correct service state checks in ProxyControlSwitches component
refactor: improve logging in service state update functions

* fix: add missing async handler for Windows and adjust logging import for macOS

* fix: streamline logging imports and add missing async handler for Windows

* refactor: remove unused useServiceStateSync hook and update imports in _layout

* refactor: remove unused useServiceStateSync import and clean up code in ProxyControlSwitches and _layout

* refactor: simplify service status checks and reduce wait time in useServiceInstaller hook

* refactor: remove unnecessary logging statements in service checks and IPC connection

* refactor: extract SwitchRow component for better code organization and readability

* refactor: enhance service state management and update related mutations in layout

* refactor: streamline core stopping logic and improve IPC connection logging

* refactor: consolidate service uninstallation logic and improve error handling

* fix: simplify conditional statements in CoreManager and service functions

* feat: add backoff dependency and implement retry strategy for IPC requests

* refactor: remove redundant Windows conditional and improve error handling in IPC tests

* test: improve error handling in IPC tests for message signing and verification

* fix: adjust IPC backoff retry parameters

* refactor: Remove service state tracking and related logic from service management

* feat: Enhance service status handling with logging and running mode updates

* fix: Improve service status handling with enhanced error logging

* fix: Ensure proper handling of service operations with error propagation

* refactor: Simplify service operation execution and enhance service status handling

* fix: Improve error message formatting in service operation execution and simplify service status retrieval

* refactor: Replace Cache with CacheProxy in multiple modules and update CacheEntry to be generic

* fix: Remove unnecessary success message from config validation

* refactor: Comment out logging statements in service version check and IPC request handling
This commit is contained in:
Tunglies
2025-09-17 22:59:02 +08:00
committed by GitHub
parent 6724f1ae35
commit c207516b47
20 changed files with 781 additions and 1386 deletions

View File

@@ -15,6 +15,8 @@ export function useSystemState() {
revalidateOnFocus: false,
},
);
const isSidecarMode = runningMode === "Sidecar";
const isServiceMode = runningMode === "Service";
// 获取管理员状态
const { data: isAdminMode = false } = useSWR("isAdmin", isAdmin, {
@@ -22,24 +24,32 @@ export function useSystemState() {
revalidateOnFocus: false,
});
// 获取系统服务状态
const isServiceMode = runningMode === "Service";
const { data: isServiceOk = false } = useSWR(
const { data: isServiceOk = false, mutate: mutateServiceOk } = useSWR(
"isServiceAvailable",
isServiceAvailable,
{
suspense: false,
revalidateOnFocus: false,
isPaused: () => !isServiceMode, // 仅在 Service 模式下请求
onSuccess: (data) => {
console.log("[useSystemState] 服务状态更新:", data);
},
onError: (error) => {
console.error("[useSystemState] 服务状态检查失败:", error);
},
isPaused: () => !isServiceMode, // 仅在非 Service 模式下暂停请求
},
);
const isTunModeAvailable = isAdminMode || isServiceOk;
return {
runningMode,
isAdminMode,
isSidecarMode: runningMode === "Sidecar",
isServiceMode: runningMode === "Service",
isSidecarMode,
isServiceMode,
isServiceOk,
isTunModeAvailable: isTunModeAvailable,
mutateRunningMode,
mutateServiceOk,
};
}

View File

@@ -1,121 +1,35 @@
import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks";
import { installService, restartCore } from "@/services/cmds";
import { showNotice } from "@/services/noticeService";
import {
installService,
isServiceAvailable,
restartCore,
} from "@/services/cmds";
import { useSystemState } from "@/hooks/use-system-state";
import { mutate } from "swr";
import { t } from "i18next";
import { useCallback } from "react";
export function useServiceInstaller() {
const { t } = useTranslation();
const { mutateRunningMode } = useSystemState();
const installServiceAndRestartCore = useLockFn(async () => {
try {
showNotice("info", t("Installing Service..."));
await installService();
showNotice("success", t("Service Installed Successfully"));
showNotice("info", t("Waiting for service to be ready..."));
let serviceReady = false;
for (let i = 0; i < 5; i++) {
try {
// 等待1秒再检查
await new Promise((resolve) => setTimeout(resolve, 1000));
const isAvailable = await isServiceAvailable();
if (isAvailable) {
serviceReady = true;
mutate("isServiceAvailable", true, false);
break;
}
// 最后一次尝试不显示重试信息
if (i < 4) {
showNotice(
"info",
t("Service not ready, retrying attempt {count}/{total}...", {
count: i + 1,
total: 5,
}),
);
}
} catch (error) {
console.error(t("Error checking service status:"), error);
if (i < 4) {
showNotice(
"error",
t(
"Failed to check service status, retrying attempt {count}/{total}...",
{
count: i + 1,
total: 5,
},
),
);
}
}
}
if (!serviceReady) {
showNotice(
"info",
t(
"Service did not become ready after attempts. Proceeding with core restart.",
),
);
}
showNotice("info", t("Restarting Core..."));
await restartCore();
// 核心重启后,再次确认并更新相关状态
await mutateRunningMode();
const finalServiceStatus = await isServiceAvailable();
mutate("isServiceAvailable", finalServiceStatus, false);
if (serviceReady && finalServiceStatus) {
showNotice("success", t("Service is ready and core restarted"));
} else if (finalServiceStatus) {
showNotice("success", t("Core restarted. Service is now available."));
} else if (serviceReady) {
showNotice(
"info",
t(
"Service was ready, but core restart might have issues or service became unavailable. Please check.",
),
);
} else {
showNotice(
"error",
t(
"Service installation or core restart encountered issues. Service might not be available. Please check system logs.",
),
);
}
return finalServiceStatus;
} catch (err: any) {
showNotice("error", err.message || err.toString());
// 尝试性回退或最终操作
try {
showNotice("info", t("Attempting to restart core as a fallback..."));
await restartCore();
await mutateRunningMode();
await isServiceAvailable().then((status) =>
mutate("isServiceAvailable", status, false),
);
} catch (recoveryError: any) {
showNotice(
"error",
t("Fallback core restart also failed: {message}", {
message: recoveryError.message,
}),
);
}
return false;
const executeWithErrorHandling = async (
operation: () => Promise<void>,
loadingMessage: string,
successMessage?: string,
) => {
try {
showNotice("info", t(loadingMessage));
await operation();
if (successMessage) {
showNotice("success", t(successMessage));
}
});
} catch (err) {
const msg = (err as Error)?.message || String(err);
showNotice("error", msg);
throw err;
}
};
export const useServiceInstaller = () => {
const installServiceAndRestartCore = useCallback(async () => {
await executeWithErrorHandling(
() => installService(),
"Installing Service...",
"Service Installed Successfully",
);
await executeWithErrorHandling(() => restartCore(), "Restarting Core...");
}, []);
return { installServiceAndRestartCore };
}
};

View File

@@ -0,0 +1,41 @@
import { restartCore, stopCore, uninstallService } from "@/services/cmds";
import { showNotice } from "@/services/noticeService";
import { t } from "i18next";
import { useSystemState } from "./use-system-state";
import { useCallback } from "react";
const executeWithErrorHandling = async (
operation: () => Promise<void>,
loadingMessage: string,
successMessage?: string,
) => {
try {
showNotice("info", t(loadingMessage));
await operation();
if (successMessage) {
showNotice("success", t(successMessage));
}
} catch (err) {
const msg = (err as Error)?.message || String(err);
showNotice("error", msg);
throw err;
}
};
export const useServiceUninstaller = () => {
const { mutateRunningMode, mutateServiceOk } = useSystemState();
const uninstallServiceAndRestartCore = useCallback(async () => {
await executeWithErrorHandling(() => stopCore(), "Stopping Core...");
await executeWithErrorHandling(
() => uninstallService(),
"Uninstalling Service...",
"Service Uninstalled Successfully",
);
await executeWithErrorHandling(() => restartCore(), "Restarting Core...");
}, [mutateRunningMode, mutateServiceOk]);
return { uninstallServiceAndRestartCore };
};