import { Request, Response } from 'express'; import { z } from 'zod'; import { createInstance, startInstance, stopInstance, removeInstance, getAllInstances, getInstance, } from '../services/instance.service'; import logger from '../utils/logger'; // 验证 schema const createInstanceSchema = z.object({ body: z.object({ name: z.string().min(1, '实例名称不能为空'), config: z.object({ model: z.string().min(1, '模型不能为空'), apiKey: z.string().optional(), workingDir: z.string().min(1, '工作目录不能为空'), port: z.number().int().min(1).max(65535).optional(), maxMemory: z.number().int().positive().optional(), env: z.record(z.string()).optional(), }), }), }); export async function createInstanceHandler(req: Request, res: Response) { try { const instance = await createInstance(req.body); res.status(201).json({ instance }); } catch (error: any) { logger.error('创建实例失败', error); res.status(400).json({ error: error.message }); } } export async function startInstanceHandler(req: Request, res: Response) { try { const { instanceId } = req.params; await startInstance(instanceId); res.json({ success: true, message: '实例启动成功' }); } catch (error: any) { logger.error('启动实例失败', error); res.status(400).json({ error: error.message }); } } export async function stopInstanceHandler(req: Request, res: Response) { try { const { instanceId } = req.params; await stopInstance(instanceId); res.json({ success: true, message: '实例停止成功' }); } catch (error: any) { logger.error('停止实例失败', error); res.status(400).json({ error: error.message }); } } export async function deleteInstanceHandler(req: Request, res: Response) { try { const { instanceId } = req.params; await removeInstance(instanceId); res.json({ success: true, message: '实例删除成功' }); } catch (error: any) { logger.error('删除实例失败', error); res.status(400).json({ error: error.message }); } } export async function listInstancesHandler(req: Request, res: Response) { try { const instances = await getAllInstances(); res.json({ instances }); } catch (error: any) { logger.error('获取实例列表失败', error); res.status(500).json({ error: '获取实例列表失败' }); } } export async function getInstanceHandler(req: Request, res: Response) { try { const { instanceId } = req.params; const instance = await getInstance(instanceId); if (!instance) { return res.status(404).json({ error: '实例不存在' }); } res.json({ instance }); } catch (error: any) { logger.error('获取实例失败', error); res.status(500).json({ error: '获取实例失败' }); } } export async function getInstanceStatusHandler(req: Request, res: Response) { try { const { instanceId } = req.params; const instance = await getInstance(instanceId); if (!instance) { return res.status(404).json({ error: '实例不存在' }); } res.json({ status: instance.status, stats: instance.stats, }); } catch (error: any) { logger.error('获取实例状态失败', error); res.status(500).json({ error: '获取实例状态失败' }); } } export { createInstanceSchema };