feat: 添加开发模式支持,本地调试不使用 PM2
实现灵活的进程管理模式,支持开发和生产环境切换: ## 新增功能 - 创建开发模式进程管理服务(dev-process.service.ts) - 使用 Node.js child_process 直接管理 Claude Code 进程 - 添加 USE_PM2 环境变量控制进程管理模式 ## 后端更改 - 新增 dev-process.service.ts:开发模式进程管理 - 更新 instance.service.ts:根据 USE_PM2 选择进程管理方式 - 更新 config:添加 usePM2 配置项 - 修复 TypeScript 类型错误 ## 配置更新 - backend/.env:设置 USE_PM2=false(开发模式) - .env.example:添加 USE_PM2 配置说明 ## 模式对比 **开发模式**(USE_PM2=false): - 使用 child_process 管理进程 - 不需要安装 PM2 - 简化的监控功能 - 适合本地开发 **生产模式**(USE_PM2=true): - 使用 PM2 管理进程 - 完整的监控和自动重启 - 需要安装 PM2 - 适合生产部署 ## 文档更新 - README.md:添加开发/生产模式对比说明 - 更新环境变量表格 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
903dc1e61f
commit
7dca4e93b1
13 files changed
+287
-72
No files matched your search
+3
-3
@@ -6,7 +6,7 @@ import { config } from './config';
|
||||
import logger from './utils/logger';
|
||||
import { initStorage } from './utils/storage';
|
||||
import { initInstanceService } from './services/instance.service';
|
||||
import { authMiddleware, optionalAuth } from './middleware/auth.middleware';
|
||||
import { authMiddleware } from './middleware/auth.middleware';
|
||||
import { errorMiddleware, notFoundMiddleware } from './middleware/error.middleware';
|
||||
import {
|
||||
verifyPassword,
|
||||
@@ -45,8 +45,8 @@ app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// 请求日志
|
||||
app.use((req, res, next) => {
|
||||
logger.info(`${req.method} ${req.path}`);
|
||||
app.use((_req, _res, next) => {
|
||||
logger.info(`${_req.method} ${_req.path}`);
|
||||
next();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ export const config = {
|
||||
// 访问密码配置
|
||||
accessPassword: process.env.ACCESS_PASSWORD || 'admin123',
|
||||
|
||||
// PM2 配置
|
||||
// 进程管理配置
|
||||
usePM2: process.env.USE_PM2 === 'true', // 是否使用 PM2(生产环境)
|
||||
pm2Home: process.env.PM2_HOME || path.join(process.env.HOME || '', '.pm2'),
|
||||
|
||||
// 实例配置
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { config } from '../config';
|
||||
import type { VerifyPasswordRequest, VerifyPasswordResponse, SessionPayload } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
@@ -20,14 +19,15 @@ setInterval(() => {
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
export async function verifyPassword(req: Request, res: Response) {
|
||||
export async function verifyPassword(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { password }: VerifyPasswordRequest = req.body;
|
||||
|
||||
// 验证密码
|
||||
if (password !== config.accessPassword) {
|
||||
logger.warn('密码验证失败');
|
||||
return res.status(401).json({ error: '密码错误' });
|
||||
res.status(401).json({ error: '密码错误' });
|
||||
return;
|
||||
}
|
||||
|
||||
// 生成会话 token
|
||||
@@ -60,7 +60,7 @@ export async function verifyPassword(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyToken(req: Request, res: Response) {
|
||||
export async function verifyToken(_req: Request, res: Response): Promise<void> {
|
||||
// 如果能到达这里,说明 token 已经被 authMiddleware 验证过
|
||||
res.json({
|
||||
valid: true,
|
||||
|
||||
@@ -25,7 +25,7 @@ const createInstanceSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export async function createInstanceHandler(req: Request, res: Response) {
|
||||
export async function createInstanceHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const instance = await createInstance(req.body);
|
||||
res.status(201).json({ instance });
|
||||
@@ -35,7 +35,7 @@ export async function createInstanceHandler(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function startInstanceHandler(req: Request, res: Response) {
|
||||
export async function startInstanceHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
await startInstance(instanceId);
|
||||
@@ -46,7 +46,7 @@ export async function startInstanceHandler(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopInstanceHandler(req: Request, res: Response) {
|
||||
export async function stopInstanceHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
await stopInstance(instanceId);
|
||||
@@ -68,7 +68,7 @@ export async function deleteInstanceHandler(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function listInstancesHandler(req: Request, res: Response) {
|
||||
export async function listInstancesHandler(_req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const instances = await getAllInstances();
|
||||
res.json({ instances });
|
||||
@@ -78,13 +78,14 @@ export async function listInstancesHandler(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInstanceHandler(req: Request, res: Response) {
|
||||
export async function getInstanceHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const instance = await getInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
return res.status(404).json({ error: '实例不存在' });
|
||||
res.status(404).json({ error: '实例不存在' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ instance });
|
||||
@@ -94,13 +95,14 @@ export async function getInstanceHandler(req: Request, res: Response) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInstanceStatusHandler(req: Request, res: Response) {
|
||||
export async function getInstanceStatusHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const instance = await getInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
return res.status(404).json({ error: '实例不存在' });
|
||||
res.status(404).json({ error: '实例不存在' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
|
||||
@@ -13,11 +13,12 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
|
||||
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return res.status(401).json({ error: '未提供认证令牌' });
|
||||
res.status(401).json({ error: '未提供认证令牌' });
|
||||
return;
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
@@ -26,23 +27,25 @@ export function authMiddleware(req: Request, res: Response, next: NextFunction)
|
||||
const decoded = jwt.verify(token, config.accessPassword) as SessionPayload;
|
||||
|
||||
if (!decoded.authenticated) {
|
||||
return res.status(401).json({ error: '无效的认证令牌' });
|
||||
res.status(401).json({ error: '无效的认证令牌' });
|
||||
return;
|
||||
}
|
||||
|
||||
req.session = decoded;
|
||||
next();
|
||||
} catch (error: any) {
|
||||
logger.error('Token 验证失败', error);
|
||||
return res.status(401).json({ error: '无效的认证令牌' });
|
||||
res.status(401).json({ error: '无效的认证令牌' });
|
||||
}
|
||||
}
|
||||
|
||||
// 可选认证(不强制要求登录)
|
||||
export function optionalAuth(req: Request, res: Response, next: NextFunction) {
|
||||
export function optionalAuth(req: Request, _res: Response, next: NextFunction): void {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return next();
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
|
||||
@@ -5,7 +5,7 @@ export function errorMiddleware(
|
||||
error: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
_next: NextFunction
|
||||
) {
|
||||
logger.error('请求处理错误', {
|
||||
error: error.message,
|
||||
|
||||
@@ -14,10 +14,11 @@ export function validate(schema: AnyZodObject) {
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
logger.error('验证失败', { errors: error.errors });
|
||||
return res.status(400).json({
|
||||
res.status(400).json({
|
||||
error: '请求数据验证失败',
|
||||
details: error.errors,
|
||||
});
|
||||
return;
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import type { InstanceConfig } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 进程存储
|
||||
const processes = new Map<string, ChildProcess>();
|
||||
|
||||
// 启动进程
|
||||
export async function startDevProcess(instanceId: string, config: InstanceConfig): Promise<void> {
|
||||
const { port, workingDir, apiKey, env } = config;
|
||||
|
||||
// 环境变量
|
||||
const processEnv: Record<string, string> = {
|
||||
...process.env,
|
||||
...env,
|
||||
PORT: port!.toString(),
|
||||
};
|
||||
|
||||
if (apiKey) {
|
||||
processEnv.ANTHROPIC_API_KEY = apiKey;
|
||||
}
|
||||
|
||||
// 启动 Claude Code HTTP 服务
|
||||
const args = ['@anthropic-ai/claude-code', 'serve', '--port', port!.toString()];
|
||||
|
||||
const childProcess = spawn('npx', args, {
|
||||
cwd: workingDir,
|
||||
env: processEnv,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
detached: false,
|
||||
});
|
||||
|
||||
// 存储进程
|
||||
processes.set(instanceId, childProcess);
|
||||
|
||||
// 处理输出
|
||||
childProcess.stdout?.on('data', (data) => {
|
||||
const message = data.toString().trim();
|
||||
if (message) {
|
||||
logger.info(`[${instanceId}] ${message}`);
|
||||
}
|
||||
});
|
||||
|
||||
childProcess.stderr?.on('data', (data) => {
|
||||
const message = data.toString().trim();
|
||||
if (message) {
|
||||
logger.error(`[${instanceId}] ${message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// 处理进程退出
|
||||
childProcess.on('exit', (code, signal) => {
|
||||
logger.info(`进程 ${instanceId} 退出`, { code, signal });
|
||||
processes.delete(instanceId);
|
||||
});
|
||||
|
||||
childProcess.on('error', (error) => {
|
||||
logger.error(`进程 ${instanceId} 错误`, error);
|
||||
processes.delete(instanceId);
|
||||
});
|
||||
|
||||
// 等待一下确保进程启动成功
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
if (childProcess.pid) {
|
||||
logger.info(`开发模式进程已启动: ${instanceId}`, { pid: childProcess.pid });
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error('进程启动失败'));
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
childProcess.once('error', (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 停止进程
|
||||
export async function stopDevProcess(instanceId: string): Promise<void> {
|
||||
const childProcess = processes.get(instanceId);
|
||||
|
||||
if (!childProcess) {
|
||||
logger.warn(`进程 ${instanceId} 不存在`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`停止开发模式进程: ${instanceId}`, { pid: childProcess.pid });
|
||||
|
||||
try {
|
||||
// 尝试优雅关闭
|
||||
process.kill(childProcess.pid!, 'SIGTERM');
|
||||
|
||||
// 等待进程退出
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
// 如果 5 秒后还没退出,强制杀死
|
||||
logger.warn(`进程 ${instanceId} 未响应 SIGTERM,强制终止`);
|
||||
childProcess.kill('SIGKILL');
|
||||
resolve();
|
||||
}, 5000);
|
||||
|
||||
childProcess.once('exit', () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
processes.delete(instanceId);
|
||||
logger.info(`开发模式进程已停止: ${instanceId}`);
|
||||
} catch (error) {
|
||||
logger.error(`停止进程 ${instanceId} 失败`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 删除进程
|
||||
export async function deleteDevProcess(instanceId: string): Promise<void> {
|
||||
await stopDevProcess(instanceId);
|
||||
}
|
||||
|
||||
// 获取进程状态
|
||||
export async function getDevProcessStatus(instanceId: string) {
|
||||
const childProcess = processes.get(instanceId);
|
||||
|
||||
if (!childProcess) {
|
||||
return {
|
||||
running: false,
|
||||
pid: undefined,
|
||||
uptime: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 计算运行时间(简化版,实际应该记录启动时间)
|
||||
const uptime = childProcess.pid ? 1 : 0; // 临时处理
|
||||
|
||||
return {
|
||||
running: childProcess.pid !== undefined,
|
||||
pid: childProcess.pid,
|
||||
uptime,
|
||||
};
|
||||
}
|
||||
|
||||
// 检查进程是否在运行
|
||||
export async function isDevProcessRunning(instanceId: string): Promise<boolean> {
|
||||
const childProcess = processes.get(instanceId);
|
||||
return childProcess !== undefined && childProcess.pid !== undefined;
|
||||
}
|
||||
|
||||
// 列出所有进程
|
||||
export function listDevProcesses() {
|
||||
return Array.from(processes.entries()).map(([id, proc]) => ({
|
||||
id,
|
||||
pid: proc.pid,
|
||||
}));
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { Instance, CreateInstanceRequest, InstanceStats } from '../types';
|
||||
import { readInstance, writeInstance, deleteInstance, listInstances, instanceExists } from '../utils/storage';
|
||||
import { readInstance, writeInstance, deleteInstance, listInstances } from '../utils/storage';
|
||||
import { allocatePort, releasePort, initPortAllocations } from '../utils/port-manager';
|
||||
import { startProcess, stopProcess, deleteProcess, isProcessRunning, describeProcess } from './pm2.service';
|
||||
import { startProcess, stopProcess, deleteProcess, describeProcess } from './pm2.service';
|
||||
import { startDevProcess, stopDevProcess, deleteDevProcess, isDevProcessRunning } from './dev-process.service';
|
||||
import { config } from '../config';
|
||||
import logger from '../utils/logger';
|
||||
import fs from 'fs/promises';
|
||||
|
||||
@@ -13,7 +15,9 @@ export async function initInstanceService() {
|
||||
.filter(i => i.config.port)
|
||||
.map(i => i.config.port!);
|
||||
initPortAllocations(ports);
|
||||
logger.info('实例服务已初始化', { instanceCount: instances.length });
|
||||
|
||||
const mode = config.usePM2 ? 'PM2' : '开发模式';
|
||||
logger.info('实例服务已初始化', { instanceCount: instances.length, mode });
|
||||
}
|
||||
|
||||
// 创建实例
|
||||
@@ -64,34 +68,39 @@ export async function startInstance(instanceId: string): Promise<void> {
|
||||
throw new Error('实例已在运行中');
|
||||
}
|
||||
|
||||
const { config, id } = instance;
|
||||
const { config: instanceConfig, id } = instance;
|
||||
|
||||
try {
|
||||
// PM2 启动选项
|
||||
const pm2Options = {
|
||||
name: id,
|
||||
script: 'npx',
|
||||
args: ['@anthropic-ai/claude-code', 'serve', '--port', config.port!.toString()],
|
||||
cwd: config.workingDir,
|
||||
env: {
|
||||
...config.env,
|
||||
ANTHROPIC_API_KEY: config.apiKey || process.env.ANTHROPIC_API_KEY,
|
||||
PORT: config.port!.toString(),
|
||||
},
|
||||
error_file: `data/logs/${id}-error.log`,
|
||||
out_file: `data/logs/${id}-out.log`,
|
||||
max_memory_restart: config.maxMemory ? `${config.maxMemory}M` : undefined,
|
||||
};
|
||||
if (config.usePM2) {
|
||||
// 生产模式:使用 PM2
|
||||
const pm2Options = {
|
||||
name: id,
|
||||
script: 'npx',
|
||||
args: ['@anthropic-ai/claude-code', 'serve', '--port', instanceConfig.port!.toString()],
|
||||
cwd: instanceConfig.workingDir,
|
||||
env: {
|
||||
...instanceConfig.env,
|
||||
ANTHROPIC_API_KEY: instanceConfig.apiKey || process.env.ANTHROPIC_API_KEY,
|
||||
PORT: instanceConfig.port!.toString(),
|
||||
},
|
||||
error_file: `data/logs/${id}-error.log`,
|
||||
out_file: `data/logs/${id}-out.log`,
|
||||
max_memory_restart: instanceConfig.maxMemory ? `${instanceConfig.maxMemory}M` : undefined,
|
||||
};
|
||||
|
||||
await startProcess(pm2Options);
|
||||
await startProcess(pm2Options);
|
||||
} else {
|
||||
// 开发模式:使用 child_process
|
||||
await startDevProcess(id, instanceConfig);
|
||||
}
|
||||
|
||||
// 更新实例状态
|
||||
instance.status = 'running';
|
||||
instance.lastStarted = new Date();
|
||||
instance.stats.port = config.port;
|
||||
instance.stats.port = instanceConfig.port;
|
||||
await writeInstance(instance);
|
||||
|
||||
logger.info('实例已启动', { instanceId, port: config.port });
|
||||
logger.info('实例已启动', { instanceId, port: instanceConfig.port, mode: config.usePM2 ? 'PM2' : 'Dev' });
|
||||
} catch (error) {
|
||||
instance.status = 'errored';
|
||||
await writeInstance(instance);
|
||||
@@ -111,7 +120,11 @@ export async function stopInstance(instanceId: string): Promise<void> {
|
||||
}
|
||||
|
||||
try {
|
||||
await stopProcess(instanceId);
|
||||
if (config.usePM2) {
|
||||
await stopProcess(instanceId);
|
||||
} else {
|
||||
await stopDevProcess(instanceId);
|
||||
}
|
||||
|
||||
instance.status = 'stopped';
|
||||
instance.stats.pid = undefined;
|
||||
@@ -119,7 +132,7 @@ export async function stopInstance(instanceId: string): Promise<void> {
|
||||
instance.stats.status = 'offline';
|
||||
await writeInstance(instance);
|
||||
|
||||
logger.info('实例已停止', { instanceId });
|
||||
logger.info('实例已停止', { instanceId, mode: config.usePM2 ? 'PM2' : 'Dev' });
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
@@ -137,9 +150,12 @@ export async function removeInstance(instanceId: string): Promise<void> {
|
||||
await stopInstance(instanceId);
|
||||
}
|
||||
|
||||
// 删除 PM2 进程
|
||||
try {
|
||||
await deleteProcess(instanceId);
|
||||
if (config.usePM2) {
|
||||
await deleteProcess(instanceId);
|
||||
} else {
|
||||
await deleteDevProcess(instanceId);
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略删除进程的错误
|
||||
}
|
||||
@@ -162,29 +178,46 @@ export async function getInstanceStatus(instanceId: string): Promise<InstanceSta
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
const process = await describeProcess(instanceId);
|
||||
if (config.usePM2) {
|
||||
// PM2 模式:从 PM2 获取详细状态
|
||||
const process = await describeProcess(instanceId);
|
||||
|
||||
if (process) {
|
||||
const isRunning = process.pm2_env.status === 'online';
|
||||
if (process) {
|
||||
const isRunning = process.pm2_env.status === 'online';
|
||||
|
||||
instance.stats = {
|
||||
pid: process.pid,
|
||||
port: instance.config.port,
|
||||
uptime: process.pm2_env.uptime,
|
||||
memory: process.monit.memory,
|
||||
cpu: process.monit.cpu,
|
||||
restarts: process.pm2_env.restart_time,
|
||||
status: isRunning ? 'online' : 'offline',
|
||||
};
|
||||
|
||||
instance.status = isRunning ? 'running' : 'stopped';
|
||||
} else {
|
||||
instance.stats.status = 'offline';
|
||||
instance.status = 'stopped';
|
||||
}
|
||||
} else {
|
||||
// 开发模式:简化状态
|
||||
const isRunning = await isDevProcessRunning(instanceId);
|
||||
|
||||
instance.stats = {
|
||||
pid: process.pid,
|
||||
pid: undefined, // 开发模式下不返回 PID
|
||||
port: instance.config.port,
|
||||
uptime: process.pm2_env.uptime,
|
||||
memory: process.monit.memory,
|
||||
cpu: process.monit.cpu,
|
||||
restarts: process.pm2_env.restart_time,
|
||||
uptime: instance.status === 'running' ? 1 : 0, // 简化
|
||||
memory: 0, // 开发模式下不监控内存
|
||||
cpu: 0, // 开发模式下不监控 CPU
|
||||
restarts: 0,
|
||||
status: isRunning ? 'online' : 'offline',
|
||||
};
|
||||
|
||||
// 更新状态
|
||||
instance.status = isRunning ? 'running' : 'stopped';
|
||||
await writeInstance(instance);
|
||||
} else {
|
||||
instance.stats.status = 'offline';
|
||||
instance.status = 'stopped';
|
||||
}
|
||||
|
||||
await writeInstance(instance);
|
||||
return instance.stats;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import winston from 'winston';
|
||||
import DailyRotateFile from 'winston-daily-rotate-file';
|
||||
import path from 'path';
|
||||
import { config } from '../config';
|
||||
|
||||
const logDir = config.logDir;
|
||||
|
||||
Reference in new issue
Block a user