Skip to content

Commit 5eef514

Browse files
author
lrhh123
committed
add: 添加插件校验逻辑
1 parent b984726 commit 5eef514

File tree

15 files changed

+788
-121
lines changed

15 files changed

+788
-121
lines changed

src/main/backend/backend.ts

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@ import bodyParser from 'body-parser';
55
import http from 'http';
66
import { Server } from 'socket.io';
77
import { BrowserWindow, shell } from 'electron';
8-
import './ormconfig';
8+
import { sequelize } from './ormconfig';
99
import { StrategyServiceStatusEnum } from './types';
1010
import { ConfigController } from './controllers/configController';
1111
import { MessageController } from './controllers/messageController';
1212
import { KeywordReplyController } from './controllers/keywordReplyController';
1313
import { MessageService } from './services/messageService';
1414
import { DispatchService } from './services/dispatchService';
1515
import { PluginService } from './services/pluginService';
16+
import { AppService } from './services/appService';
1617

1718
const configController = new ConfigController();
1819
const messageController = new MessageController();
@@ -33,6 +34,8 @@ class BKServer {
3334

3435
private dispatchService: DispatchService;
3536

37+
private appService: AppService;
38+
3639
constructor(port: number, mainWindow: BrowserWindow) {
3740
this.app = express();
3841
this.app.use(bodyParser.json());
@@ -72,8 +75,14 @@ class BKServer {
7275
this.pluginService,
7376
);
7477

78+
this.appService = new AppService(this.dispatchService, sequelize);
79+
7580
this.configureSocketIO();
7681
this.setupRoutes();
82+
// 开启定时任务
83+
setInterval(() => {
84+
this.appService.initTasks();
85+
}, 5 * 1000);
7786
}
7887

7988
private configureSocketIO(): void {
@@ -383,10 +392,31 @@ class BKServer {
383392
// }
384393
});
385394

395+
// 检查插件是否正常工作
396+
this.app.post('/api/v1/base/plugin/check', async (req, res) => {
397+
try {
398+
const { code, message, ctx } = req.body;
399+
const ctxMap = new Map(Object.entries(ctx));
400+
const resp = await this.pluginService.checkPlugin(
401+
code,
402+
// @ts-ignore
403+
ctxMap,
404+
message,
405+
);
406+
res.json(resp);
407+
} catch (error) {
408+
res.json({
409+
success: false,
410+
error: error instanceof Error ? error.message : String(error),
411+
message: error instanceof Error ? error.message : String(error),
412+
});
413+
}
414+
});
415+
386416
// 获取任务列表
387417
this.app.get('/api/v1/strategy/tasks', async (req, res) => {
388418
try {
389-
const tasks = await this.dispatchService.getTasks();
419+
const tasks = await this.appService.getTasks();
390420
res.json({
391421
success: true,
392422
data: tasks,
@@ -404,7 +434,7 @@ class BKServer {
404434
this.app.post('/api/v1/strategy/tasks', async (req, res) => {
405435
const { appId } = req.body;
406436
try {
407-
const task = await this.dispatchService.addTask(String(appId));
437+
const task = await this.appService.addTask(String(appId));
408438
res.json({
409439
success: true,
410440
data: task,
@@ -422,7 +452,7 @@ class BKServer {
422452
this.app.post('/api/v1/strategy/task/remove', async (req, res) => {
423453
const { taskId } = req.body;
424454
try {
425-
await this.dispatchService.removeTask(String(taskId));
455+
await this.appService.removeTask(String(taskId));
426456
res.json({
427457
success: true,
428458
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { DataTypes, Model, Sequelize } from 'sequelize';
2+
3+
export class Instance extends Model {
4+
declare id: number; // instance_id
5+
6+
declare app_id: string;
7+
8+
declare env_id: string;
9+
10+
declare created_at: string;
11+
}
12+
13+
export function initInstance(sequelize: Sequelize) {
14+
Instance.init(
15+
{
16+
id: {
17+
type: DataTypes.INTEGER,
18+
autoIncrement: true,
19+
primaryKey: true,
20+
},
21+
app_id: {
22+
type: DataTypes.STRING(255),
23+
allowNull: false,
24+
},
25+
env_id: {
26+
type: DataTypes.STRING(255),
27+
allowNull: true,
28+
},
29+
created_at: {
30+
type: DataTypes.DATE,
31+
allowNull: false,
32+
},
33+
},
34+
{
35+
sequelize,
36+
modelName: 'Instance',
37+
tableName: 'instance',
38+
timestamps: false,
39+
},
40+
);
41+
}

src/main/backend/ormconfig.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { Config, initConfig } from './entities/config';
99
import { initSession } from './entities/session';
1010
import { initMessage } from './entities/message';
1111
import { initPlugin } from './entities/plugin';
12+
import { initInstance } from './entities/instance';
1213
import { Keyword, initKeyword } from './entities/keyword';
1314

1415
// Get user's documents directory path
@@ -25,7 +26,7 @@ const DB_FILE_PATH = path.join(APP_DIR, 'msg.db');
2526

2627
console.log('DB_FILE_PATH:', DB_FILE_PATH);
2728

28-
const sequelize = new Sequelize({
29+
export const sequelize = new Sequelize({
2930
dialect: 'sqlite',
3031
dialectModule: sqlite,
3132
storage: DB_FILE_PATH,
@@ -38,6 +39,7 @@ initSession(sequelize);
3839
initMessage(sequelize);
3940
initKeyword(sequelize);
4041
initPlugin(sequelize);
42+
initInstance(sequelize);
4143

4244
// 异步初始化和数据填充函数
4345
async function initDb(): Promise<void> {
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import { Sequelize, Transaction } from 'sequelize';
2+
import { DispatchService } from './dispatchService';
3+
import { Instance } from '../entities/instance';
4+
import { Config } from '../entities/config';
5+
import { Plugin } from '../entities/plugin';
6+
7+
export class AppService {
8+
private dispatchService: DispatchService;
9+
10+
private sequelize: Sequelize;
11+
12+
constructor(dispatchService: DispatchService, sequelize: Sequelize) {
13+
this.dispatchService = dispatchService;
14+
this.sequelize = sequelize;
15+
}
16+
17+
public async getTasks(): Promise<
18+
{
19+
task_id: string;
20+
env_id: string;
21+
app_id: string;
22+
}[]
23+
> {
24+
const instances = await Instance.findAll();
25+
return instances.map((instance) => ({
26+
task_id: String(instance.id),
27+
env_id: instance.env_id,
28+
app_id: instance.app_id,
29+
}));
30+
}
31+
32+
/**
33+
* 初始化全部任务
34+
*/
35+
public async initTasks(): Promise<void> {
36+
const instances = await Instance.findAll();
37+
await this.dispatchService.updateTasks(instances);
38+
}
39+
40+
/**
41+
* 添加一个任务
42+
*/
43+
public async addTask(appId: string): Promise<Instance | null> {
44+
// 使用事务
45+
return this.sequelize
46+
.transaction(async (t: Transaction) => {
47+
const instance = await Instance.create(
48+
{
49+
app_id: appId,
50+
created_at: new Date(),
51+
},
52+
{ transaction: t },
53+
);
54+
55+
// 取得全部 Tasks 然后全部更新
56+
const tasks = await Instance.findAll();
57+
tasks.push(instance);
58+
const result = await this.dispatchService.updateTasks(tasks);
59+
if (!result || result.length === 0) {
60+
throw new Error('Failed to update tasks');
61+
}
62+
63+
const target = result.find(
64+
(task) => task.task_id === String(instance.id),
65+
);
66+
if (!target) {
67+
throw new Error('Failed to find target task');
68+
}
69+
70+
instance.env_id = target.env_id;
71+
await instance.save({ transaction: t });
72+
return instance;
73+
})
74+
.catch((error) => {
75+
// 处理错误
76+
console.error('Transaction failed:', error);
77+
throw error; // 可根据需求自定义错误处理逻辑
78+
});
79+
}
80+
81+
/**
82+
* 移除一个任务
83+
*/
84+
public async removeTask(taskId: string): Promise<boolean> {
85+
const instance = await Instance.findByPk(taskId);
86+
87+
if (!instance) {
88+
return false;
89+
}
90+
91+
await instance.destroy();
92+
93+
// 找到对应的 Config 删除
94+
const config = await Config.findOne({
95+
where: { instance_id: taskId },
96+
});
97+
if (config) {
98+
// 检查是否使用插件
99+
if (config.plugin_id) {
100+
const plugin = await Plugin.findOne({
101+
where: { id: config.plugin_id },
102+
});
103+
if (plugin) {
104+
await plugin.destroy();
105+
}
106+
}
107+
108+
await config.destroy();
109+
}
110+
111+
// 取得全部 Tasks 然后全部更新
112+
const tasks = await Instance.findAll();
113+
await this.dispatchService.updateTasks(tasks);
114+
115+
return true;
116+
}
117+
}

src/main/backend/services/dispatchService.ts

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { MessageService } from './messageService';
66
import PluginService from './pluginService';
77
import { ConfigController } from '../controllers/configController';
88
import { MessageController } from '../controllers/messageController';
9+
import { Instance } from '../entities/instance';
910

1011
export class DispatchService {
1112
private mainWindow: BrowserWindow;
@@ -83,37 +84,27 @@ export class DispatchService {
8384
}
8485
}
8586

86-
public async getTasks(): Promise<any> {
87+
public async updateTasks(tasks: Instance[]): Promise<
88+
| {
89+
task_id: string;
90+
env_id: string;
91+
}[]
92+
| null
93+
> {
8794
try {
88-
return await emitAndWait(this.io, 'strategyService-getTasks', {});
89-
} catch (error) {
90-
console.error('Failed to get tasks', error);
91-
return null;
92-
}
93-
}
94-
95-
public async addTask(appId: string): Promise<any> {
96-
try {
97-
return await emitAndWait(this.io, 'strategyService-addTask', {
98-
app_id: appId,
95+
return await emitAndWait(this.io, 'strategyService-updateTasks', {
96+
tasks: tasks.map((task) => ({
97+
task_id: task.id,
98+
app_id: task.app_id,
99+
env_id: task.env_id,
100+
})),
99101
});
100102
} catch (error) {
101103
console.error('Failed to add task', error);
102104
return null;
103105
}
104106
}
105107

106-
public async removeTask(taskId: string): Promise<any> {
107-
try {
108-
return await emitAndWait(this.io, 'strategyService-removeTask', {
109-
task_id: taskId,
110-
});
111-
} catch (error) {
112-
console.error('Failed to remove task', error);
113-
return null;
114-
}
115-
}
116-
117108
public async updateStatus(status: StrategyServiceStatusEnum): Promise<any> {
118109
try {
119110
return await emitAndWait(this.io, 'strategyService-updateStatus', {

0 commit comments

Comments
 (0)