@kne/fastify-task 2.0.7 → 3.0.0-alpha.1

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.
package/index.js CHANGED
@@ -11,12 +11,16 @@ module.exports = fp(
11
11
  name: 'task',
12
12
  limit: 10,
13
13
  dir: path.resolve(process.cwd(), 'libs', 'tasks'),
14
+ /** 任务目录列表,运行时可通过 addDir 动态添加 */
15
+ dirs: null,
14
16
  cronTime: '*/10 * * * *',
15
17
  scriptName: 'index',
16
18
  maxPollTimes: 20,
17
19
  pollInterval: 10000,
18
- /** 每小时任务完成按 UTC 桶重算(默认每时第 5 分执行,聚合上一完整 UTC 小时);传 null/false 关闭 */
19
- hourlyStatisticsCronTime: '5 * * * *',
20
+ /** 任务执行超时时间(毫秒),0 表示不超时,默认 30 分钟 */
21
+ taskTimeout: 30 * 60 * 1000,
22
+ /** 重试基础延迟(毫秒),实际延迟 = retryBaseDelay * 2^(retryCount-1) */
23
+ retryBaseDelay: 5000,
20
24
  getUserModel: () => {
21
25
  return fastify.account.models.user;
22
26
  },
@@ -28,10 +32,18 @@ module.exports = fp(
28
32
  options
29
33
  );
30
34
 
31
- if (!fastify.sse) {
32
- fastify.register(require('@fastify/sse'));
35
+ // 初始化 dirs:优先使用用户传入的 dirs,否则以 dir 为默认值,保证向后兼容
36
+ if (!options.dirs) {
37
+ options.dirs = [options.dir];
38
+ } else if (!options.dirs.includes(options.dir)) {
39
+ options.dirs = [options.dir, ...options.dirs];
33
40
  }
34
41
 
42
+ fastify.register(require('@kne/fastify-statistics'), {
43
+ dbTableNamePrefix: options.dbTableNamePrefix,
44
+ name: `${options.name}Statistics`
45
+ });
46
+
35
47
  fastify.register(require('@kne/fastify-namespace'), {
36
48
  options,
37
49
  name: options.name,
@@ -63,17 +75,6 @@ module.exports = fp(
63
75
  //启动时,将running状态的任务设置为pending
64
76
  fastify.addHook('onReady', async () => {
65
77
  await fastify[options.name].services.resetAll();
66
- fastify[options.name].services.syncHourlyStatisticsFromTasks().catch(console.error);
67
- });
68
- }
69
- if (options.hourlyStatisticsCronTime) {
70
- fastify.cron.createJob({
71
- cronTime: options.hourlyStatisticsCronTime,
72
- onTick: async () => {
73
- const { syncHourlyStatisticsFromTasks } = fastify[options.name].services;
74
- await syncHourlyStatisticsFromTasks();
75
- },
76
- start: true
77
78
  });
78
79
  }
79
80
  })
@@ -2,6 +2,68 @@ const fp = require('fastify-plugin');
2
2
 
3
3
  module.exports = fp(async (fastify, options) => {
4
4
  const { services } = fastify[options.name];
5
+ // #14: 新增创建任务的 REST 接口
6
+ fastify.post(
7
+ `${options.prefix}/create`,
8
+ {
9
+ onRequest: options.getAuthenticate('write'),
10
+ schema: {
11
+ summary: '创建任务',
12
+ body: {
13
+ type: 'object',
14
+ properties: {
15
+ type: {
16
+ type: 'string',
17
+ description: '任务类型'
18
+ },
19
+ targetId: {
20
+ type: 'string',
21
+ description: '目标对象ID'
22
+ },
23
+ targetType: {
24
+ type: 'string',
25
+ description: '目标对象类型'
26
+ },
27
+ input: {
28
+ type: 'object',
29
+ description: '输入数据'
30
+ },
31
+ runnerType: {
32
+ type: 'string',
33
+ enum: ['manual', 'system'],
34
+ description: '执行者类型'
35
+ },
36
+ delay: {
37
+ type: 'number',
38
+ description: '延迟执行秒数'
39
+ },
40
+ scriptName: {
41
+ type: 'string',
42
+ description: '任务脚本名称'
43
+ },
44
+ priority: {
45
+ type: 'number',
46
+ description: '优先级,数值越大越优先,默认0'
47
+ },
48
+ parentTaskId: {
49
+ type: 'string',
50
+ description: '父任务ID,用于任务依赖'
51
+ },
52
+ maxRetries: {
53
+ type: 'number',
54
+ description: '最大自动重试次数,默认0'
55
+ }
56
+ },
57
+ required: ['type', 'targetId', 'targetType']
58
+ }
59
+ }
60
+ },
61
+ async request => {
62
+ const task = await services.create(Object.assign({}, request.body, { userId: request.userInfo?.id }));
63
+ return { id: task.id };
64
+ }
65
+ );
66
+
5
67
  fastify.get(
6
68
  `${options.prefix}/list`,
7
69
  {
@@ -125,7 +187,20 @@ module.exports = fp(async (fastify, options) => {
125
187
  type: 'object',
126
188
  properties: {
127
189
  id: {
128
- type: 'string'
190
+ type: 'string',
191
+ description: '任务ID'
192
+ },
193
+ targetId: {
194
+ type: 'string',
195
+ description: '目标对象ID(批量取消时使用)'
196
+ },
197
+ targetType: {
198
+ type: 'string',
199
+ description: '目标对象类型(批量取消时使用)'
200
+ },
201
+ type: {
202
+ type: 'string',
203
+ description: '任务类型(批量取消时使用)'
129
204
  }
130
205
  }
131
206
  }
@@ -1,6 +1,5 @@
1
1
  const fp = require('fastify-plugin');
2
2
 
3
- /** 看板统计:概览 GET /statistics 与 SSE /statistics/sse(独立 controller 插件,见业务插件开发指南「路由标准化」) */
4
3
  module.exports = fp(async (fastify, options) => {
5
4
  const { services } = fastify[options.name];
6
5
 
@@ -13,142 +12,17 @@ module.exports = fp(async (fastify, options) => {
13
12
  query: {
14
13
  type: 'object',
15
14
  properties: {
16
- range: { type: 'string', default: '7d', description: '时间范围: 7d=近7天, 1m=近1个月, 1y=近1年' },
15
+ range: { type: 'string', default: '7d', description: '时间范围: 7d=近7天, 1m=近1个月, 3m=近3个月, 1y=近1年' },
17
16
  timezone: { type: 'string', description: '时区,如 Asia/Shanghai,默认服务器时区' },
18
17
  type: { type: 'string', description: '按任务类型筛选' },
19
18
  runnerType: { type: 'string', description: '按执行方式筛选 manual / system' }
20
19
  }
21
- },
22
- response: {
23
- 200: {
24
- type: 'object',
25
- properties: {
26
- range: { type: 'string', description: '当前时间范围' },
27
- rangeLabel: { type: 'string', description: '时间范围描述' },
28
- totalTasks: { type: 'integer', description: '时间范围内任务总数' },
29
- byStatus: {
30
- type: 'object',
31
- description: '按任务状态统计',
32
- additionalProperties: { type: 'integer' }
33
- },
34
- byType: {
35
- type: 'object',
36
- description: '按任务类型统计',
37
- additionalProperties: { type: 'integer' }
38
- },
39
- byRunnerType: {
40
- type: 'object',
41
- description: '按执行者类型统计(manual/system)',
42
- additionalProperties: { type: 'integer' }
43
- },
44
- byTargetType: {
45
- type: 'object',
46
- description: '按目标对象类型统计',
47
- additionalProperties: { type: 'integer' }
48
- },
49
- recentTrend: {
50
- type: 'array',
51
- description: '按日任务创建趋势',
52
- items: {
53
- type: 'object',
54
- properties: {
55
- date: { type: 'string', description: '日期' },
56
- count: { type: 'integer', description: '任务数量' }
57
- }
58
- }
59
- },
60
- recentTrendByStatus: {
61
- type: 'array',
62
- description: '按日+状态任务创建趋势',
63
- items: {
64
- type: 'object',
65
- properties: {
66
- date: { type: 'string', description: '日期' },
67
- status: { type: 'string', description: '任务状态' },
68
- count: { type: 'integer', description: '任务数量' }
69
- }
70
- }
71
- },
72
- recentTrendByType: {
73
- type: 'array',
74
- description: '按日+类型任务创建趋势',
75
- items: {
76
- type: 'object',
77
- properties: {
78
- date: { type: 'string', description: '日期' },
79
- type: { type: 'string', description: '任务类型' },
80
- count: { type: 'integer', description: '任务数量' }
81
- }
82
- }
83
- },
84
- durationTrend: {
85
- type: 'array',
86
- description: '按日平均耗时趋势(来自预聚合统计表)',
87
- items: {
88
- type: 'object',
89
- properties: {
90
- date: { type: 'string', description: '完成日期' },
91
- completedCount: { type: 'integer', description: '完成任务数' },
92
- successCount: { type: 'integer', description: '成功数' },
93
- failedCount: { type: 'integer', description: '失败数' },
94
- canceledCount: { type: 'integer', description: '取消数' },
95
- avgWaitingTime: { type: 'integer', description: '平均等待时间(毫秒)' },
96
- avgExecutionTime: { type: 'integer', description: '平均执行时间(毫秒)' },
97
- avgTotalTime: { type: 'integer', description: '平均总耗时(毫秒)' },
98
- byType: {
99
- type: 'object',
100
- description: '按类型分组的耗时统计',
101
- additionalProperties: {
102
- type: 'object',
103
- properties: {
104
- count: { type: 'integer' },
105
- avgWaitingTime: { type: 'integer' },
106
- avgExecutionTime: { type: 'integer' },
107
- avgTotalTime: { type: 'integer' }
108
- }
109
- }
110
- },
111
- byRunnerType: {
112
- type: 'object',
113
- description: '按执行者类型分组的耗时统计',
114
- additionalProperties: {
115
- type: 'object',
116
- properties: {
117
- count: { type: 'integer' },
118
- avgWaitingTime: { type: 'integer' },
119
- avgExecutionTime: { type: 'integer' },
120
- avgTotalTime: { type: 'integer' }
121
- }
122
- }
123
- }
124
- }
125
- }
126
- },
127
- hourlyCompletionTrend: {
128
- type: 'array',
129
- description: '按完成时刻归入 UTC 小时桶后,在请求 timezone 下展开的每小时+类型+执行方式完成数',
130
- items: {
131
- type: 'object',
132
- properties: {
133
- date: { type: 'string', description: '客户端时区下的日期 YYYY-MM-DD' },
134
- hour: { type: 'integer', description: '客户端时区下的小时 0-23' },
135
- type: { type: 'string' },
136
- runnerType: { type: 'string' },
137
- totalCompleted: { type: 'integer' },
138
- successCount: { type: 'integer' },
139
- failedCount: { type: 'integer' },
140
- canceledCount: { type: 'integer' }
141
- }
142
- }
143
- }
144
- }
145
- }
146
20
  }
147
21
  }
148
22
  },
149
23
  async request => {
150
24
  const { range = '7d', timezone, type, runnerType } = request.query;
151
- return await services.statistics.getOverview({ range, timezone, type, runnerType });
25
+ return await services.queryStatistics({ range, timezone, type, runnerType });
152
26
  }
153
27
  );
154
28
 
@@ -156,43 +30,24 @@ module.exports = fp(async (fastify, options) => {
156
30
  fastify.get(
157
31
  `${options.prefix}/statistics/sse`,
158
32
  {
159
- sse: true,
160
33
  onRequest: options.getAuthenticate('statistics'),
161
34
  schema: {
162
- summary: 'SSE实时推送当天任务统计数据',
35
+ summary: 'SSE实时推送任务统计数据',
163
36
  query: {
164
37
  type: 'object',
165
38
  properties: {
166
- interval: { type: 'integer', minimum: 1, default: 5, description: '推送间隔时间(秒),最小1秒,默认5秒' },
39
+ range: { type: 'string', default: '7d', description: '时间范围: 7d=近7天, 1m=近1个月, 3m=近3个月, 1y=近1年' },
167
40
  timezone: { type: 'string', description: '时区,如 Asia/Shanghai,默认服务器时区' },
168
41
  type: { type: 'string', description: '按任务类型筛选' },
169
- runnerType: { type: 'string', description: '按执行方式筛选 manual / system' }
42
+ runnerType: { type: 'string', description: '按执行方式筛选 manual / system' },
43
+ interval: { type: 'integer', minimum: 1, default: 5, description: '推送间隔时间(秒),最小1秒,默认5秒' }
170
44
  }
171
45
  }
172
46
  }
173
47
  },
174
- async function (request, reply) {
175
- const intervalSeconds = request.query.interval ?? 5;
176
- const { timezone, type, runnerType } = request.query;
177
- const startTime = Date.now();
178
- const maxDurationMs = 30 * 60 * 1000;
179
-
180
- async function* eventStream() {
181
- while (reply.sse.isConnected) {
182
- if (Date.now() - startTime >= maxDurationMs) {
183
- yield { event: 'timeout', data: JSON.stringify({ message: '连接已超过30分钟,自动断开' }) };
184
- return;
185
- }
186
- try {
187
- yield { data: JSON.stringify(await services.statistics.getRealtime({ timezone, type, runnerType })) };
188
- } catch (err) {
189
- yield { event: 'error', data: JSON.stringify({ message: err.message }) };
190
- }
191
- await new Promise(resolve => setTimeout(resolve, intervalSeconds * 1000));
192
- }
193
- }
194
-
195
- await reply.sse.send(eventStream());
48
+ async (request, reply) => {
49
+ const { range = '7d', timezone, type, runnerType, interval } = request.query;
50
+ await services.sseStatistics({ range, timezone, type, runnerType, interval }, reply);
196
51
  }
197
52
  );
198
53
  });
@@ -24,6 +24,25 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
24
24
  defaultValue: 'manual',
25
25
  allowNull: false
26
26
  },
27
+ priority: {
28
+ type: DataTypes.INTEGER,
29
+ comment: '任务优先级,数值越大越优先',
30
+ defaultValue: 0
31
+ },
32
+ parentTaskId: definePrimaryType('parentTaskId', {
33
+ comment: '父任务ID,用于任务依赖/链式执行',
34
+ allowNull: true
35
+ }),
36
+ retryCount: {
37
+ type: DataTypes.INTEGER,
38
+ comment: '已重试次数',
39
+ defaultValue: 0
40
+ },
41
+ maxRetries: {
42
+ type: DataTypes.INTEGER,
43
+ comment: '最大重试次数,0表示不自动重试',
44
+ defaultValue: 0
45
+ },
27
46
  startTime: {
28
47
  type: DataTypes.DATE,
29
48
  comment: '任务最早执行时间',
@@ -37,13 +56,18 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
37
56
  type: DataTypes.DATE,
38
57
  comment: '任务完成时间'
39
58
  },
59
+ completedUserId: definePrimaryType('completedUserId', {
60
+ comment: '完成任务的用户ID'
61
+ }),
40
62
  input: {
41
63
  type: DataTypes.JSON,
42
- comment: '输入数据'
64
+ comment: '输入数据',
65
+ defaultValue: null
43
66
  },
44
67
  output: {
45
68
  type: DataTypes.JSON,
46
- comment: '输出数据'
69
+ comment: '输出数据',
70
+ defaultValue: null
47
71
  },
48
72
  error: {
49
73
  type: DataTypes.JSON,
@@ -94,6 +118,11 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
94
118
  as: 'completedUser',
95
119
  comment: '任务完成人'
96
120
  });
121
+ task.belongsTo(task, {
122
+ foreignKey: 'parentTaskId',
123
+ as: 'parentTask',
124
+ comment: '父任务'
125
+ });
97
126
  },
98
127
  options: {
99
128
  comment: '任务',
@@ -104,7 +133,9 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
104
133
  { fields: ['runner_type'] },
105
134
  { fields: ['type', 'status'] },
106
135
  { fields: ['runner_type', 'status'] },
107
- { fields: ['target_id', 'target_type', 'type'] }
136
+ { fields: ['target_id', 'target_type', 'type'] },
137
+ { fields: ['parent_task_id'] },
138
+ { fields: ['priority'] }
108
139
  ]
109
140
  }
110
141
  };