@pisell/core 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/es/app/app.d.ts +7 -7
  2. package/es/app/index.d.ts +1 -1
  3. package/es/applicationManager/application.d.ts +2 -2
  4. package/es/cmd/const.d.ts +5 -5
  5. package/es/hooks/useStore/index.d.ts +1 -1
  6. package/es/indexDB/index.d.ts +2 -2
  7. package/es/indexDB/index.js +633 -572
  8. package/es/locales/type.d.ts +3 -3
  9. package/es/logger/index.d.ts +1 -1
  10. package/es/models/index.d.ts +4 -4
  11. package/es/pubsub/index.d.ts +1 -1
  12. package/es/request/cache.d.ts +1 -1
  13. package/es/request/pisell2Request.d.ts +1 -1
  14. package/es/request/type.d.ts +1 -1
  15. package/es/routes/index.d.ts +2 -2
  16. package/es/socket/monitor.js +2 -0
  17. package/es/socket/types.d.ts +4 -3
  18. package/es/tasks/index.d.ts +0 -1
  19. package/es/tasks/index.js +0 -1
  20. package/es/tasks/type.d.ts +4 -4
  21. package/es/variables/index.d.ts +3 -3
  22. package/lib/app/app.d.ts +7 -7
  23. package/lib/app/app.js +21 -51
  24. package/lib/app/index.d.ts +1 -1
  25. package/lib/applicationManager/application.d.ts +2 -2
  26. package/lib/applicationManager/application.js +6 -12
  27. package/lib/applicationManager/index.js +4 -2
  28. package/lib/aws/index.js +0 -3
  29. package/lib/cmd/const.d.ts +5 -5
  30. package/lib/cmd/const.js +5 -5
  31. package/lib/cmd/index.js +0 -2
  32. package/lib/cookie/index.js +4 -2
  33. package/lib/data/index.js +0 -3
  34. package/lib/history/index.js +22 -24
  35. package/lib/hooks/useStore/index.d.ts +1 -1
  36. package/lib/indexDB/index.d.ts +2 -2
  37. package/lib/indexDB/index.js +233 -327
  38. package/lib/locales/index.js +94 -95
  39. package/lib/locales/type.d.ts +3 -3
  40. package/lib/logger/index.d.ts +1 -1
  41. package/lib/logger/index.js +8 -18
  42. package/lib/menuManager/index.js +12 -9
  43. package/lib/models/index.d.ts +4 -4
  44. package/lib/pubsub/index.d.ts +1 -1
  45. package/lib/pubsub/index.js +3 -1
  46. package/lib/request/cache.d.ts +1 -1
  47. package/lib/request/pisell2Request.d.ts +1 -1
  48. package/lib/request/type.d.ts +1 -1
  49. package/lib/routes/index.d.ts +2 -2
  50. package/lib/routes/index.js +1 -3
  51. package/lib/socket/components/SocketMonitorPage.js +12 -6
  52. package/lib/socket/heartbeat.js +5 -10
  53. package/lib/socket/index.js +3 -1
  54. package/lib/socket/monitor.js +26 -26
  55. package/lib/socket/reconnect.js +3 -10
  56. package/lib/socket/socket.js +10 -12
  57. package/lib/socket/types.d.ts +4 -3
  58. package/lib/storage/index.js +24 -25
  59. package/lib/tasks/index.d.ts +0 -1
  60. package/lib/tasks/index.js +329 -334
  61. package/lib/tasks/type.d.ts +4 -4
  62. package/lib/variables/index.d.ts +3 -3
  63. package/package.json +3 -2
@@ -35,279 +35,197 @@ module.exports = __toCommonJS(tasks_exports);
35
35
  var import_dayjs = __toESM(require("dayjs"));
36
36
  var import_utils = require("@pisell/utils");
37
37
  var import_useTasks = __toESM(require("./useTasks"));
38
- var TasksManager = class _TasksManager {
39
- static instance;
40
- taskFunctions;
41
- tasks = {
42
- // 内置模块, 定时任务专用
43
- scheduledTasks: {}
44
- };
45
- app;
46
- db;
47
- useTasks = import_useTasks.default;
48
- watchTaskCallback = () => {
49
- };
50
- timerIds = [];
38
+ var TasksManager = class {
51
39
  constructor(app) {
52
- if (!app) {
53
- throw new Error("app is required");
54
- }
55
- this.app = app;
56
- this.taskFunctions = /* @__PURE__ */ new Map();
57
40
  this.tasks = {
41
+ // 内置模块, 定时任务专用
58
42
  scheduledTasks: {}
59
43
  };
60
- this.db = app.dbManager;
44
+ this.useTasks = import_useTasks.default;
45
+ this.watchTaskCallback = () => {
46
+ };
61
47
  this.timerIds = [];
62
- }
63
- // 单例模式
64
- static getInstance(app) {
65
- if (!_TasksManager.instance && app) {
66
- _TasksManager.instance = new _TasksManager(app);
67
- }
68
- return _TasksManager.instance;
69
- }
70
- // 注册任务函数
71
- addTaskFunction(name, fun) {
72
- this.taskFunctions.set(name, fun);
73
- console.log("Tasks--->", `注册任务函数成功: ${name}`);
74
- }
75
- // 注册任务函数列表
76
- addTaskFunctions(tasks) {
77
- tasks.forEach(({ name, fun }) => {
78
- this.taskFunctions.set(name, fun);
79
- });
80
- }
81
- getTasks() {
82
- return this.tasks;
83
- }
84
- // 获取任务函数
85
- getTaskFunction(name) {
86
- if (!name) {
87
- return null;
88
- }
89
- return this.taskFunctions.get(name);
90
- }
91
- // 初始化任务
92
- async init() {
93
- const tasks = await this.loadTaskQueueFromLocal();
94
- if (tasks) {
95
- console.log("initTasks", tasks);
96
- }
97
- }
98
- // 将任务队列状态同步到 local
99
- saveTaskQueueToLocal = async (state) => {
100
- var _a;
101
- console.log("saveTaskQueueToLocal", state);
102
- let tasksData = await this.db.get("tasks", "tasks");
103
- const newData = { id: "tasks", ...state };
104
- if (!tasksData) {
105
- await this.db.add("tasks", newData);
106
- } else {
107
- await this.db.update("tasks", newData);
108
- }
109
- (_a = this.watchTaskCallback) == null ? void 0 : _a.call(this, this.tasks);
110
- };
111
- // 从 local 加载任务队列状态
112
- loadTaskQueueFromLocal = async () => {
113
- var _a, _b;
114
- try {
115
- const tasks = await this.db.get("tasks", "tasks");
116
- for (let module2 in tasks) {
117
- for (let queueId in tasks[module2]) {
118
- for (let task of ((_b = (_a = tasks == null ? void 0 : tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks) || []) {
119
- if (task.destroy) {
120
- delete tasks[module2][queueId].tasks;
48
+ // 将任务队列状态同步到 local
49
+ this.saveTaskQueueToLocal = async (state) => {
50
+ var _a;
51
+ console.log("saveTaskQueueToLocal", state);
52
+ let tasksData = await this.db.get("tasks", "tasks");
53
+ const newData = { id: "tasks", ...state };
54
+ if (!tasksData) {
55
+ await this.db.add("tasks", newData);
56
+ } else {
57
+ await this.db.update("tasks", newData);
58
+ }
59
+ (_a = this.watchTaskCallback) == null ? void 0 : _a.call(this, this.tasks);
60
+ };
61
+ // 从 local 加载任务队列状态
62
+ this.loadTaskQueueFromLocal = async () => {
63
+ var _a, _b;
64
+ try {
65
+ const tasks = await this.db.get("tasks", "tasks");
66
+ for (let module2 in tasks) {
67
+ for (let queueId in tasks[module2]) {
68
+ for (let task of ((_b = (_a = tasks == null ? void 0 : tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks) || []) {
69
+ if (task.destroy) {
70
+ delete tasks[module2][queueId].tasks;
71
+ }
121
72
  }
122
73
  }
123
74
  }
75
+ return tasks;
76
+ } catch (err) {
77
+ console.log("loadTaskQueueFromLocal", err);
78
+ return null;
124
79
  }
125
- return tasks;
126
- } catch (err) {
127
- console.log("loadTaskQueueFromLocal", err);
128
- return null;
129
- }
130
- };
131
- /**
132
- * @title: 执行任务
133
- * @description:
134
- * @param {Task} task
135
- * @return {*}
136
- * @Author: zhiwei.Wang
137
- * @Date: 2024-09-26 13:53
138
- */
139
- runTask = async (task) => {
140
- const beforeAction = this.getTaskFunction(task.beforeAction || "");
141
- const afterAction = this.getTaskFunction(task.afterAction || "");
142
- const action = this.getTaskFunction(task.action || "");
143
- let beforeActionRes;
144
- let afterActionRes;
145
- let actionRes = { status: "success" };
146
- try {
147
- if (beforeAction) {
148
- beforeActionRes = await beforeAction({ task });
149
- }
150
- if (action) {
151
- actionRes = await action({ task, beforeActionRes });
152
- }
153
- if (afterAction) {
154
- afterActionRes = await afterAction({ task, actionRes, afterActionRes });
80
+ };
81
+ /**
82
+ * @title: 执行任务
83
+ * @description:
84
+ * @param {Task} task
85
+ * @return {*}
86
+ * @Author: zhiwei.Wang
87
+ * @Date: 2024-09-26 13:53
88
+ */
89
+ this.runTask = async (task) => {
90
+ const beforeAction = this.getTaskFunction(task.beforeAction || "");
91
+ const afterAction = this.getTaskFunction(task.afterAction || "");
92
+ const action = this.getTaskFunction(task.action || "");
93
+ let beforeActionRes;
94
+ let afterActionRes;
95
+ let actionRes = { status: "success" };
96
+ try {
97
+ if (beforeAction) {
98
+ beforeActionRes = await beforeAction({ task });
99
+ }
100
+ if (action) {
101
+ actionRes = await action({ task, beforeActionRes });
102
+ }
103
+ if (afterAction) {
104
+ afterActionRes = await afterAction({ task, actionRes, afterActionRes });
105
+ }
106
+ } catch (error) {
107
+ this.app.logger.addLog({
108
+ type: "info",
109
+ title: `任务执行失败-${task.id}`,
110
+ metadata: { error, taskPayload: task == null ? void 0 : task.payload }
111
+ });
112
+ actionRes = { status: "failure" };
155
113
  }
156
- } catch (error) {
157
- this.app.logger.addLog({
158
- type: "info",
159
- title: `任务执行失败-${task.id}`,
160
- metadata: { error, taskPayload: task == null ? void 0 : task.payload }
114
+ console.log("Tasks--->", `任务执行成功: ${task.id}`);
115
+ return actionRes;
116
+ };
117
+ /**
118
+ * @title: 清除任务定时器
119
+ */
120
+ this.clearTaskTimer = (params) => {
121
+ const { timerId, taskId } = params;
122
+ const _timerIds = [];
123
+ const needClearTimerIds = [];
124
+ this.timerIds.forEach((id) => {
125
+ const taskIdRult = taskId ? (id == null ? void 0 : id.taskId) === taskId : true;
126
+ const timerIdRult = timerId ? (id == null ? void 0 : id.timerId) === timerId : true;
127
+ if (taskIdRult && timerIdRult) {
128
+ needClearTimerIds.push(id);
129
+ } else {
130
+ _timerIds.push(id);
131
+ }
161
132
  });
162
- actionRes = { status: "failure" };
163
- }
164
- console.log("Tasks--->", `任务执行成功: ${task.id}`);
165
- return actionRes;
166
- };
167
- /**
168
- * @title: 清除任务定时器
169
- * @param {NodeJS.Timeout} timerId
170
- */
171
- clearTaskTimer = (params) => {
172
- const { timerId, taskId } = params;
173
- const _timerIds = [];
174
- const needClearTimerIds = [];
175
- this.timerIds.forEach((id) => {
176
- const taskIdRult = taskId ? (id == null ? void 0 : id.taskId) === taskId : true;
177
- const timerIdRult = timerId ? (id == null ? void 0 : id.timerId) === timerId : true;
178
- if (taskIdRult && timerIdRult) {
179
- needClearTimerIds.push(id);
180
- } else {
181
- _timerIds.push(id);
182
- }
183
- });
184
- if (needClearTimerIds.length) {
185
- for (let id of needClearTimerIds) {
186
- clearTimeout(id.timerId);
187
- }
188
- }
189
- this.timerIds = [..._timerIds || []];
190
- };
191
- /**
192
- * @title: 计算下一次执行时间
193
- * @description: 根据定时任务配置计算下一次执行时间
194
- * @param {Task} task
195
- * @return {string | null} 下一次执行时间
196
- */
197
- calculateNextExecuteTime = (task) => {
198
- if (!task.scheduled) {
199
- return null;
200
- }
201
- const { scheduled, scheduledResult } = task;
202
- const now = (0, import_dayjs.default)();
203
- if (scheduled.endAt && now.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
204
- return null;
205
- }
206
- if (Array.isArray(scheduled.executeAt)) {
207
- const futureTime = scheduled.executeAt.map((time) => (0, import_dayjs.default)(time)).filter((time) => time.isAfter(now)).sort((a, b) => a.valueOf() - b.valueOf())[0];
208
- if (futureTime) {
209
- return futureTime.format("YYYY-MM-DD HH:mm:ss");
133
+ if (needClearTimerIds.length) {
134
+ for (let id of needClearTimerIds) {
135
+ clearTimeout(id.timerId);
136
+ }
210
137
  }
211
- if (!scheduled.repeat) {
138
+ this.timerIds = [..._timerIds || []];
139
+ };
140
+ /**
141
+ * @title: 计算下一次执行时间
142
+ * @description: 根据定时任务配置计算下一次执行时间
143
+ * @param {Task} task
144
+ * @return {string | null} 下一次执行时间
145
+ */
146
+ this.calculateNextExecuteTime = (task) => {
147
+ if (!task.scheduled) {
212
148
  return null;
213
149
  }
214
- }
215
- if (scheduled.repeat && (scheduledResult == null ? void 0 : scheduledResult.nextExecuteTime)) {
216
- const lastExecuteTime = (0, import_dayjs.default)(scheduledResult.nextExecuteTime);
217
- const interval = scheduled.repeatInterval || 1;
218
- let nextTime = lastExecuteTime;
219
- switch (scheduled.repeatType) {
220
- case "daily":
221
- nextTime = lastExecuteTime.add(interval, "day");
222
- break;
223
- case "weekly":
224
- nextTime = lastExecuteTime.add(interval, "week");
225
- break;
226
- case "monthly":
227
- nextTime = lastExecuteTime.add(interval, "month");
228
- break;
229
- case "yearly":
230
- nextTime = lastExecuteTime.add(interval, "year");
231
- break;
232
- default:
233
- nextTime = lastExecuteTime.add(interval, "day");
234
- }
235
- if (scheduled.endAt && nextTime.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
150
+ const { scheduled, scheduledResult } = task;
151
+ const now = (0, import_dayjs.default)();
152
+ if (scheduled.endAt && now.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
236
153
  return null;
237
154
  }
238
- return nextTime.format("YYYY-MM-DD HH:mm:ss");
239
- }
240
- const executeTime = Array.isArray(scheduled.executeAt) ? scheduled.executeAt[0] : scheduled.executeAt;
241
- return (0, import_dayjs.default)(executeTime).format("YYYY-MM-DD HH:mm:ss");
242
- };
243
- /**
244
- * @title: 启动定时任务
245
- * @description: 在特定时间点执行任务(仅在 scheduledTasks 模块中生效)
246
- * @param {Task} task
247
- * @return {*}
248
- */
249
- startScheduledTask = (task) => {
250
- var _a;
251
- if (!task.scheduled) {
252
- console.log("Tasks--->", "不是定时任务");
253
- return;
254
- }
255
- if (task.module !== "scheduledTasks") {
256
- console.warn("Tasks--->", `定时任务只在 scheduledTasks 模块中生效,任务 ${task.id} 将作为普通任务执行`);
257
- return;
258
- }
259
- const nextExecuteTime = this.calculateNextExecuteTime(task);
260
- if (!nextExecuteTime) {
261
- console.log("Tasks--->", "定时任务已完成或无下次执行时间", task);
262
- this.deleteTask({
263
- module: task.module,
264
- queueId: task.queueId,
265
- taskId: task.id
266
- });
267
- return;
268
- }
269
- const now = (0, import_dayjs.default)();
270
- const executeTime = (0, import_dayjs.default)(nextExecuteTime);
271
- const delay = executeTime.diff(now);
272
- if (delay < 0) {
273
- console.log("Tasks--->", "执行时间已过,跳过此次执行");
274
- if (task.scheduled.repeat) {
275
- const _task = { ...task };
276
- _task.scheduledResult = {
277
- count: ((_a = _task.scheduledResult) == null ? void 0 : _a.count) || 0,
278
- nextExecuteTime
279
- };
280
- const newTask = this.updateTask({
281
- module: task.module,
282
- queueId: task.queueId,
283
- taskId: task.id,
284
- other: _task
285
- });
286
- if (newTask) {
287
- this.startScheduledTask(newTask);
155
+ if (Array.isArray(scheduled.executeAt)) {
156
+ const futureTime = scheduled.executeAt.map((time) => (0, import_dayjs.default)(time)).filter((time) => time.isAfter(now)).sort((a, b) => a.valueOf() - b.valueOf())[0];
157
+ if (futureTime) {
158
+ return futureTime.format("YYYY-MM-DD HH:mm:ss");
288
159
  }
289
- } else {
160
+ if (!scheduled.repeat) {
161
+ return null;
162
+ }
163
+ }
164
+ if (scheduled.repeat && (scheduledResult == null ? void 0 : scheduledResult.nextExecuteTime)) {
165
+ const lastExecuteTime = (0, import_dayjs.default)(scheduledResult.nextExecuteTime);
166
+ const interval = scheduled.repeatInterval || 1;
167
+ let nextTime = lastExecuteTime;
168
+ switch (scheduled.repeatType) {
169
+ case "daily":
170
+ nextTime = lastExecuteTime.add(interval, "day");
171
+ break;
172
+ case "weekly":
173
+ nextTime = lastExecuteTime.add(interval, "week");
174
+ break;
175
+ case "monthly":
176
+ nextTime = lastExecuteTime.add(interval, "month");
177
+ break;
178
+ case "yearly":
179
+ nextTime = lastExecuteTime.add(interval, "year");
180
+ break;
181
+ default:
182
+ nextTime = lastExecuteTime.add(interval, "day");
183
+ }
184
+ if (scheduled.endAt && nextTime.isAfter((0, import_dayjs.default)(scheduled.endAt))) {
185
+ return null;
186
+ }
187
+ return nextTime.format("YYYY-MM-DD HH:mm:ss");
188
+ }
189
+ const executeTime = Array.isArray(scheduled.executeAt) ? scheduled.executeAt[0] : scheduled.executeAt;
190
+ return (0, import_dayjs.default)(executeTime).format("YYYY-MM-DD HH:mm:ss");
191
+ };
192
+ /**
193
+ * @title: 启动定时任务
194
+ * @description: 在特定时间点执行任务(仅在 scheduledTasks 模块中生效)
195
+ * @param {Task} task
196
+ * @return {*}
197
+ */
198
+ this.startScheduledTask = (task) => {
199
+ var _a;
200
+ if (!task.scheduled) {
201
+ console.log("Tasks--->", "不是定时任务");
202
+ return;
203
+ }
204
+ if (task.module !== "scheduledTasks") {
205
+ console.warn("Tasks--->", `定时任务只在 scheduledTasks 模块中生效,任务 ${task.id} 将作为普通任务执行`);
206
+ return;
207
+ }
208
+ const nextExecuteTime = this.calculateNextExecuteTime(task);
209
+ if (!nextExecuteTime) {
210
+ console.log("Tasks--->", "定时任务已完成或无下次执行时间", task);
290
211
  this.deleteTask({
291
212
  module: task.module,
292
213
  queueId: task.queueId,
293
214
  taskId: task.id
294
215
  });
216
+ return;
295
217
  }
296
- return;
297
- }
298
- console.log("Tasks--->", `定时任务将在 ${nextExecuteTime} 执行 (${delay}ms 后)`, task);
299
- const timerId = setTimeout(async () => {
300
- var _a2, _b;
301
- try {
302
- await this.runTask(task);
303
- console.log("Tasks--->", "定时任务执行完成", task);
304
- let _task = { ...task };
305
- _task.scheduledResult = {
306
- count: (((_a2 = _task.scheduledResult) == null ? void 0 : _a2.count) || 0) + 1,
307
- timerId,
308
- nextExecuteTime
309
- };
310
- if ((_b = task.scheduled) == null ? void 0 : _b.repeat) {
218
+ const now = (0, import_dayjs.default)();
219
+ const executeTime = (0, import_dayjs.default)(nextExecuteTime);
220
+ const delay = executeTime.diff(now);
221
+ if (delay < 0) {
222
+ console.log("Tasks--->", "执行时间已过,跳过此次执行");
223
+ if (task.scheduled.repeat) {
224
+ const _task = { ...task };
225
+ _task.scheduledResult = {
226
+ count: ((_a = _task.scheduledResult) == null ? void 0 : _a.count) || 0,
227
+ nextExecuteTime
228
+ };
311
229
  const newTask = this.updateTask({
312
230
  module: task.module,
313
231
  queueId: task.queueId,
@@ -324,95 +242,172 @@ var TasksManager = class _TasksManager {
324
242
  taskId: task.id
325
243
  });
326
244
  }
327
- } catch (error) {
328
- this.clearTaskTimer({ timerId });
329
- console.error("定时任务执行异常", error);
245
+ return;
330
246
  }
331
- }, delay);
332
- this.timerIds.push({ taskId: task.id, timerId });
333
- };
334
- /**
335
- * @title: 启动轮询
336
- * @description: 根据轮询间隔定期执行任务
337
- * @param {Task} task
338
- * @return {*}
339
- */
340
- startPolling = (task) => {
341
- if (!task.polling || !task.polling.interval) {
342
- console.log("不是轮询任务");
343
- return;
344
- }
345
- const timerId = setTimeout(async () => {
346
- var _a;
347
- try {
348
- await this.runTask(task);
349
- console.log("轮询任务", task);
350
- let _task = { ...task };
351
- _task.pollingResult = {
352
- count: (((_a = _task.pollingResult) == null ? void 0 : _a.count) || 0) + 1,
353
- timerId
354
- };
355
- const newTask = this.updateTask({
356
- module: task.module,
357
- queueId: task.queueId,
358
- taskId: task.id,
359
- other: _task
360
- });
361
- if (!newTask) {
362
- return;
247
+ console.log("Tasks--->", `定时任务将在 ${nextExecuteTime} 执行 (${delay}ms 后)`, task);
248
+ const timerId = setTimeout(async () => {
249
+ var _a2, _b;
250
+ try {
251
+ await this.runTask(task);
252
+ console.log("Tasks--->", "定时任务执行完成", task);
253
+ let _task = { ...task };
254
+ _task.scheduledResult = {
255
+ count: (((_a2 = _task.scheduledResult) == null ? void 0 : _a2.count) || 0) + 1,
256
+ timerId,
257
+ nextExecuteTime
258
+ };
259
+ if ((_b = task.scheduled) == null ? void 0 : _b.repeat) {
260
+ const newTask = this.updateTask({
261
+ module: task.module,
262
+ queueId: task.queueId,
263
+ taskId: task.id,
264
+ other: _task
265
+ });
266
+ if (newTask) {
267
+ this.startScheduledTask(newTask);
268
+ }
269
+ } else {
270
+ this.deleteTask({
271
+ module: task.module,
272
+ queueId: task.queueId,
273
+ taskId: task.id
274
+ });
275
+ }
276
+ } catch (error) {
277
+ this.clearTaskTimer({ timerId });
278
+ console.error("定时任务执行异常", error);
363
279
  }
364
- this.startPolling(newTask);
365
- } catch (error) {
366
- this.clearTaskTimer({ timerId });
367
- console.error("轮询任务异常", error);
280
+ }, delay);
281
+ this.timerIds.push({ taskId: task.id, timerId });
282
+ };
283
+ /**
284
+ * @title: 启动轮询
285
+ * @description: 根据轮询间隔定期执行任务
286
+ * @param {Task} task
287
+ * @return {*}
288
+ */
289
+ this.startPolling = (task) => {
290
+ if (!task.polling || !task.polling.interval) {
291
+ console.log("不是轮询任务");
292
+ return;
368
293
  }
369
- }, task.polling.interval);
370
- this.timerIds.push({ taskId: task.id, timerId });
371
- };
372
- /**
373
- * @title: 创建任务数据
374
- * @description:
375
- * @param {Partial} payload
376
- * @return {*}
377
- * @Author: zhiwei.Wang
378
- * @Date: 2024-09-26 13:54
379
- */
380
- createTaskData = (payload) => {
381
- return {
382
- id: (0, import_utils.getUniqueId)("task_"),
383
- create_at: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
384
- type: "local",
385
- retries: 0,
386
- maxRetries: 3,
387
- status: "pending",
388
- // 执行函数
389
- action: "",
390
- // 执行参数
391
- payload: {},
392
- // 执行前的钩子
393
- beforeAction: "",
394
- // 执行前的参数
395
- beforePayload: {},
396
- // 执行后的钩子
397
- afterAction: "",
398
- // 执行后的参数
399
- afterPayload: {},
400
- destroy: true,
401
- ...payload
294
+ const timerId = setTimeout(async () => {
295
+ var _a;
296
+ try {
297
+ await this.runTask(task);
298
+ console.log("轮询任务", task);
299
+ let _task = { ...task };
300
+ _task.pollingResult = {
301
+ count: (((_a = _task.pollingResult) == null ? void 0 : _a.count) || 0) + 1,
302
+ timerId
303
+ };
304
+ const newTask = this.updateTask({
305
+ module: task.module,
306
+ queueId: task.queueId,
307
+ taskId: task.id,
308
+ other: _task
309
+ });
310
+ if (!newTask) {
311
+ return;
312
+ }
313
+ this.startPolling(newTask);
314
+ } catch (error) {
315
+ this.clearTaskTimer({ timerId });
316
+ console.error("轮询任务异常", error);
317
+ }
318
+ }, task.polling.interval);
319
+ this.timerIds.push({ taskId: task.id, timerId });
402
320
  };
403
- };
404
- getTaskQueue = (payload) => {
405
- var _a, _b;
406
- const { queueId, module: module2 } = payload;
407
- return (_b = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks;
408
- };
409
- timeout = (ms) => {
410
- return new Promise((resolve) => {
411
- setTimeout(() => {
412
- resolve(true);
413
- }, ms || 5e3);
321
+ /**
322
+ * @title: 创建任务数据
323
+ * @description:
324
+ * @param {Partial} payload
325
+ * @return {*}
326
+ * @Author: zhiwei.Wang
327
+ * @Date: 2024-09-26 13:54
328
+ */
329
+ this.createTaskData = (payload) => {
330
+ return {
331
+ id: (0, import_utils.getUniqueId)("task_"),
332
+ create_at: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
333
+ type: "local",
334
+ retries: 0,
335
+ maxRetries: 3,
336
+ status: "pending",
337
+ // 执行函数
338
+ action: "",
339
+ // 执行参数
340
+ payload: {},
341
+ // 执行前的钩子
342
+ beforeAction: "",
343
+ // 执行前的参数
344
+ beforePayload: {},
345
+ // 执行后的钩子
346
+ afterAction: "",
347
+ // 执行后的参数
348
+ afterPayload: {},
349
+ destroy: true,
350
+ ...payload
351
+ };
352
+ };
353
+ this.getTaskQueue = (payload) => {
354
+ var _a, _b;
355
+ const { queueId, module: module2 } = payload;
356
+ return (_b = (_a = this.tasks[module2]) == null ? void 0 : _a[queueId]) == null ? void 0 : _b.tasks;
357
+ };
358
+ this.timeout = (ms) => {
359
+ return new Promise((resolve) => {
360
+ setTimeout(() => {
361
+ resolve(true);
362
+ }, ms || 5e3);
363
+ });
364
+ };
365
+ if (!app) {
366
+ throw new Error("app is required");
367
+ }
368
+ this.app = app;
369
+ this.taskFunctions = /* @__PURE__ */ new Map();
370
+ this.tasks = {
371
+ scheduledTasks: {}
372
+ };
373
+ this.db = app.dbManager;
374
+ this.timerIds = [];
375
+ }
376
+ // 单例模式
377
+ static getInstance(app) {
378
+ if (!TasksManager.instance && app) {
379
+ TasksManager.instance = new TasksManager(app);
380
+ }
381
+ return TasksManager.instance;
382
+ }
383
+ // 注册任务函数
384
+ addTaskFunction(name, fun) {
385
+ this.taskFunctions.set(name, fun);
386
+ console.log("Tasks--->", `注册任务函数成功: ${name}`);
387
+ }
388
+ // 注册任务函数列表
389
+ addTaskFunctions(tasks) {
390
+ tasks.forEach(({ name, fun }) => {
391
+ this.taskFunctions.set(name, fun);
414
392
  });
415
- };
393
+ }
394
+ getTasks() {
395
+ return this.tasks;
396
+ }
397
+ // 获取任务函数
398
+ getTaskFunction(name) {
399
+ if (!name) {
400
+ return null;
401
+ }
402
+ return this.taskFunctions.get(name);
403
+ }
404
+ // 初始化任务
405
+ async init() {
406
+ const tasks = await this.loadTaskQueueFromLocal();
407
+ if (tasks) {
408
+ console.log("initTasks", tasks);
409
+ }
410
+ }
416
411
  /**
417
412
  * @title: 执行任务队列
418
413
  * @description: