chore: 移除系统服务功能,桌面壳直接托管后端子进程

This commit is contained in:
liufumingren 2026-08-24 02:20:39 +08:00
parent f56ca33a8d
commit fff6a2f46b
8 changed files with 43 additions and 410 deletions

View File

@ -33,8 +33,6 @@ printServer 是一个面向 Windows 的本地打印服务应用。
- 业务服务,如打印机、设置、绑定
- views/
- 页面模板,目前主要是 index.html
- daemon/
- 守护或服务相关配置文件
- 临时/
- 临时分析文档、测试脚本、临时日志的统一目录,可在任务结束后整体清理
@ -65,8 +63,7 @@ npm run dev
- WebSocket 服务按 method 路由到 services/ 下对应实例方法
示例:
- setting.register -> services/setting.js
- setting.unregister -> services/setting.js
- setting.info -> services/setting.js
- printer.getWindowsPrinters -> services/printer.js
## 当前打包方向

View File

@ -209,10 +209,8 @@ function Invoke-SignFile([string]$TargetPath, [string]$Label) {
function Sign-AppArtifacts {
$appExePath = Join-Path $root 'dist\win-unpacked\printServer.exe'
$serviceWrapperPath = Join-Path $root 'dist\win-unpacked\resources\daemon\printserver.exe'
Invoke-SignFile -TargetPath $appExePath -Label 'app executable'
Invoke-SignFile -TargetPath $serviceWrapperPath -Label 'service wrapper'
}
function Sign-InstallerArtifacts {
@ -354,7 +352,7 @@ function Ensure-PackagedResources() {
Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force
}
foreach ($dirName in @('daemon', 'frpc')) {
foreach ($dirName in @('frpc')) {
$sourcePath = Join-Path $root $dirName
$targetPath = Join-Path $resourcesDir $dirName

Binary file not shown.

View File

@ -1,6 +0,0 @@
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
<supportedRuntime version="v4.0" />
</startup>
</configuration>

View File

@ -1,12 +0,0 @@
<service>
<id>printserver.exe</id>
<name>PrintServer</name>
<description>printServer backend service</description>
<executable>D:\printServer\node_modules\electron\dist\electron.exe</executable>
<argument>D:\printServer</argument>
<argument>--service-runner</argument>
<logmode>rotate</logmode>
<startmode>Automatic</startmode>
<stoptimeout>30sec</stoptimeout>
<workingdirectory>D:\printServer</workingdirectory>
</service>

View File

@ -1,13 +1,9 @@
import service from '../core/BaseService.js';
import configUtil from '../utils/config.js';
import { startService, uninstallService } from '../utils/windowsService.js';
function isServiceRunnerProcess() {
return process.argv.includes('--service-runner');
}
import { isElectronRuntime } from '../utils/runtime.js';
function isManagedBackendRunnerProcess() {
return process.argv.includes('--backend-runner') || process.argv.includes('--service-runner');
return process.argv.includes('--backend-runner');
}
function scheduleCurrentProcessExit() {
@ -26,8 +22,6 @@ class SettingService extends service {
super();
this.info = this.info.bind(this);
this.unbind = this.unbind.bind(this);
this.register = this.register.bind(this);
this.unregister = this.unregister.bind(this);
this.updatePorts = this.updatePorts.bind(this);
this.restartBackend = this.restartBackend.bind(this);
this.setToken = this.setToken.bind(this);
@ -43,7 +37,6 @@ class SettingService extends service {
return {
isBind: !!config.token,
name: config.name || '',
isService: !!config.isService,
wsPort: Number(config.wsPort) || 17301,
recording: {
isRecording: !!hik.isRecording,
@ -81,6 +74,7 @@ class SettingService extends service {
const { app } = this;
const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 17301;
// 托管后端子进程(打包态):退出后由桌面壳 reconcile 循环重新拉起
if (isManagedBackendRunnerProcess()) {
scheduleCurrentProcessExit();
return {
@ -91,6 +85,42 @@ class SettingService extends service {
};
}
// Electron 主进程内嵌后端(开发模式):无法自我重启,重启整个桌面应用
if (isElectronRuntime()) {
if (targetWsPort !== Number(app.config?.wsPort)) {
app.config.wsPort = targetWsPort;
configUtil.write(app.config);
}
try {
const electron = await import('electron');
const electronApp = electron.app || electron.default?.app;
if (!electronApp || typeof electronApp.relaunch !== 'function') {
throw new Error('electron app 对象不可用');
}
// 给 WS 响应留出时间,再重启整个应用
setTimeout(() => {
try {
electronApp.relaunch();
electronApp.exit(0);
} catch (error) {
console.error('[SettingService] 应用重启失败:', error);
}
}, 500);
return {
ok: true,
restarting: true,
wsPort: targetWsPort,
message: '应用正在重启,请稍候'
};
} catch (error) {
return {
ok: false,
restarting: false,
message: `应用重启失败:${error.message}`
};
}
}
if (!app || typeof app.restartBackendRuntime !== 'function') {
return {
ok: false,
@ -134,74 +164,8 @@ class SettingService extends service {
return { ok: true, message: '解绑成功' };
}
// WebSocket 注册服务,切换为“系统服务管理后端”的状态(已弃用,系统服务功能已移除)
// WebSocket 注册服务,切换为“系统服务管理后端”的状态
async register() {
const { config } = this;
const previousIsService = !!config.isService;
try {
await startService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注册失败:${error.message}`,
isService: previousIsService
};
}
config.isService = true;
configUtil.write(config);
this.app.isService = true;
if (!isServiceRunnerProcess()) {
scheduleCurrentProcessExit();
}
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已启用'
: '服务模式已启用,当前前台后端将退出,由系统服务接管',
isService: true
};
}
// WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态
async unregister() {
const { config } = this;
const previousIsService = !!config.isService;
if (!isServiceRunnerProcess()) {
try {
await uninstallService();
} catch (error) {
config.isService = previousIsService;
configUtil.write(config);
this.app.isService = previousIsService;
return {
ok: false,
message: `系统服务注销失败:${error.message}`,
isService: previousIsService
};
}
}
config.isService = false;
configUtil.write(config);
this.app.isService = false;
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务'
: '服务已注销,后端将恢复为桌面壳直接启动',
isService: false
};
}
async setToken(data) {
const { config } = this;
config.token = data.token;

View File

@ -1,289 +0,0 @@
import fs from 'fs';
import path from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { getProjectRoot, getResourcePath, isElectronRuntime, isPackagedElectron } from './runtime.js';
const execFileAsync = promisify(execFile);
const SERVICE_NAME = 'PrintServer';
const SERVICE_ID = 'printserver.exe';
function assertWindows() {
if (process.platform !== 'win32') {
throw new Error('Windows 服务能力仅支持 Windows 环境');
}
}
function escapeXml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function getServiceWrapperPath() {
return getResourcePath('daemon', SERVICE_ID);
}
function getServiceXmlPath() {
return getResourcePath('daemon', 'printserver.xml');
}
function getServiceWorkingDirectory() {
if (isPackagedElectron()) {
return path.dirname(process.execPath);
}
return getProjectRoot();
}
function getServiceCommandDefinition() {
if (isElectronRuntime()) {
return {
executable: process.execPath,
arguments: isPackagedElectron() ? ['--service-runner'] : [getProjectRoot(), '--service-runner'],
workingDirectory: getServiceWorkingDirectory()
};
}
return {
executable: process.execPath,
arguments: [path.join(getProjectRoot(), 'index.js')],
workingDirectory: getProjectRoot()
};
}
function buildServiceXml() {
const command = getServiceCommandDefinition();
const argumentLines = command.arguments
.map((argument) => ` <argument>${escapeXml(argument)}</argument>`)
.join('\n');
return [
'<service>',
` <id>${SERVICE_ID}</id>`,
` <name>${SERVICE_NAME}</name>`,
' <description>printServer backend service</description>',
` <executable>${escapeXml(command.executable)}</executable>`,
argumentLines,
' <logmode>rotate</logmode>',
' <startmode>Automatic</startmode>',
' <stoptimeout>30sec</stoptimeout>',
` <workingdirectory>${escapeXml(command.workingDirectory)}</workingdirectory>`,
'</service>',
''
].join('\n');
}
export function ensureServiceDefinition() {
assertWindows();
const wrapperPath = getServiceWrapperPath();
const xmlPath = getServiceXmlPath();
if (!fs.existsSync(wrapperPath)) {
throw new Error(`服务包装器不存在: ${wrapperPath}`);
}
const expectedXml = buildServiceXml();
const currentXml = fs.existsSync(xmlPath) ? fs.readFileSync(xmlPath, 'utf8') : '';
if (currentXml !== expectedXml) {
fs.writeFileSync(xmlPath, expectedXml, 'utf8');
}
return {
name: SERVICE_NAME,
id: SERVICE_ID,
wrapperPath,
xmlPath,
workingDirectory: getServiceWorkingDirectory()
};
}
function isAccessDeniedErrorMessage(message) {
if (!message) {
return false;
}
return /AccessDenied|拒绝访问|\b0x5\b|\berror\s*5\b/i.test(String(message));
}
function isServiceAlreadyExistsErrorMessage(message) {
if (!message) {
return false;
}
return /already exists|已存在|Service with id\s*'?.+?'?\s*already exists/i.test(String(message));
}
function isServiceAlreadyRunningErrorMessage(message) {
if (!message) {
return false;
}
return /already started|already running|已启动|正在运行/i.test(String(message));
}
async function runWrapperCommandElevated(command, metadata) {
const escapedWrapperPath = metadata.wrapperPath.replace(/'/g, "''");
const escapedCommand = String(command).replace(/'/g, "''");
const escapedWorkingDirectory = path.dirname(metadata.wrapperPath).replace(/'/g, "''");
const psCommand = [
"$proc = Start-Process",
`-FilePath '${escapedWrapperPath}'`,
`-ArgumentList '${escapedCommand}'`,
`-WorkingDirectory '${escapedWorkingDirectory}'`,
'-Verb RunAs',
'-WindowStyle Hidden',
'-PassThru',
'-Wait;',
'exit $proc.ExitCode'
].join(' ');
try {
await execFileAsync('powershell.exe', ['-NoProfile', '-Command', psCommand], {
windowsHide: true
});
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
throw new Error(`提权执行服务命令 ${command} 失败: ${details}`);
}
return {
stdout: '',
stderr: ''
};
}
async function runWrapperCommand(command, options = {}) {
const {
allowElevation = true
} = options;
const metadata = ensureServiceDefinition();
try {
const result = await execFileAsync(metadata.wrapperPath, [command], {
cwd: path.dirname(metadata.wrapperPath),
windowsHide: true
});
return {
stdout: (result.stdout || '').trim(),
stderr: (result.stderr || '').trim()
};
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
if (allowElevation && command !== 'status' && isAccessDeniedErrorMessage(details)) {
try {
return await runWrapperCommandElevated(command, metadata);
} catch (elevatedError) {
throw new Error(`执行服务命令 ${command} 失败: ${details} | ${elevatedError.message}`);
}
}
throw new Error(`执行服务命令 ${command} 失败: ${details}`);
}
}
function parseServiceStatus(rawStatus) {
const normalized = (rawStatus || '').trim();
if (!normalized || normalized === 'NonExistent') {
return {
installed: false,
running: false,
rawStatus: normalized || 'NonExistent'
};
}
return {
installed: true,
running: /started|running|active/i.test(normalized),
rawStatus: normalized
};
}
export async function getServiceStatus(options = {}) {
const { stdout } = await runWrapperCommand('status', options);
return parseServiceStatus(stdout);
}
export async function ensureServiceInstalled(options = {}) {
let status = null;
try {
status = await getServiceStatus(options);
} catch (error) {
status = null;
}
if (status && status.installed) {
return status;
}
try {
await runWrapperCommand('install', options);
} catch (error) {
if (!isServiceAlreadyExistsErrorMessage(error.message)) {
throw error;
}
}
try {
return await getServiceStatus(options);
} catch (error) {
// 某些机器上 status 读取异常,但 install 已提示“已存在”。此时按已安装处理。
return {
installed: true,
running: false,
rawStatus: 'Existing'
};
}
}
export async function startService(options = {}) {
const status = await ensureServiceInstalled(options);
if (status.running) {
return status;
}
try {
await runWrapperCommand('start', options);
} catch (error) {
if (!isServiceAlreadyRunningErrorMessage(error.message)) {
throw error;
}
}
return getServiceStatus(options);
}
export async function stopService(options = {}) {
const status = await getServiceStatus(options);
if (!status.installed || !status.running) {
return status;
}
await runWrapperCommand('stop', options);
return getServiceStatus(options);
}
export async function uninstallService(options = {}) {
const status = await getServiceStatus(options);
if (!status.installed) {
return status;
}
if (status.running) {
await runWrapperCommand('stop', options);
}
await runWrapperCommand('uninstall', options);
return getServiceStatus(options);
}

View File

@ -227,10 +227,6 @@
<span class="status-label">本地服务:</span>
<span class="status-value" :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title }}</span>
</div>
<div class="status-item">
<span class="status-label">服务注册:</span>
<span class="status-value" :style="{color: isServices ? 'green' : 'red'}" @click="isServices ? unregister() : register()" style="cursor:pointer;">{{ isServices ? '已注册' : '未注册' }}</span>
</div>
<div class="status-item">
<span class="status-label">服务器连接:</span>
<span class="status-value" :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title }}</span>
@ -350,8 +346,7 @@ new Vue({
'disconnected': { title: '未连接', color: 'red' },
'connected': { title: '已连接', color: 'green' },
'error': { title: '连接错误', color: 'red' },
},
isServices: false
}
},
methods: {
loadComponents() {
@ -387,20 +382,6 @@ new Vue({
}
});
},
register() {
wsSendWithCallback('setting.register', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
unregister() {
wsSendWithCallback('setting.unregister', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
isBind() {
wsSendWithCallback('setting.info', {}, (data) => {
if (data.success) {