@kne/fastify-task 1.1.0 → 1.1.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/README.md CHANGED
@@ -124,34 +124,36 @@ npm i --save @kne/fastify-task
124
124
 
125
125
  **POST** `{prefix}/next`
126
126
 
127
- | 参数名 | 类型 | 必填 | 说明 |
128
- |-----------|--------|----|---------------|
129
- | id | string | 是 | 任务ID |
130
- | signature | string | 否 | HMAC-SHA256签名 |
131
- | result | string | 是 | JSON格式的结果 |
127
+ | 参数名 | 类型 | 必填 | 说明 |
128
+ |-----------|--------|----|----------------------------------------|
129
+ | id | string | 是 | 任务ID |
130
+ | signature | string | 否 | HMAC-SHA256签名(当任务设置了context.secret时必填) |
131
+ | result | string | 是 | JSON格式的结果 |
132
132
 
133
133
  #### 记录任务日志
134
134
 
135
135
  **POST** `{prefix}/log`
136
136
 
137
- | 参数名 | 类型 | 必填 | 说明 |
138
- |---------|--------|----|-------------|
139
- | id | string | 是 | 任务ID(body) |
140
- | taskId | string | 是 | 任务ID(query) |
141
- | data | object | 否 | 日志数据 |
142
- | message | string | 否 | 日志消息 |
137
+ | 参数名 | 类型 | 必填 | 说明 |
138
+ |-----------|--------|----|----------------------------------------|
139
+ | id | string | 是 | 任务ID(body) |
140
+ | taskId | string | 是 | 任务ID(query) |
141
+ | data | object | 否 | 日志数据 |
142
+ | message | string | 否 | 日志消息 |
143
+ | signature | string | 否 | HMAC-SHA256签名(当任务设置了context.secret时必填) |
143
144
 
144
145
  #### 任务回调
145
146
 
146
147
  **POST** `{prefix}/callback`
147
148
 
148
- | 参数名 | 类型 | 必填 | 说明 |
149
- |---------|--------|----|-------------|
150
- | id | string | 是 | 任务ID(body) |
151
- | taskId | string | 是 | 任务ID(query) |
152
- | code | number | 是 | 状态码,0为成功 |
153
- | data | object | 否 | 回调数据 |
154
- | message | string | 否 | 回调消息 |
149
+ | 参数名 | 类型 | 必填 | 说明 |
150
+ |-----------|--------|----|----------------------------------------|
151
+ | id | string | 是 | 任务ID(body) |
152
+ | taskId | string | 是 | 任务ID(query) |
153
+ | code | number | 是 | 状态码,0为成功 |
154
+ | data | object | 否 | 回调数据 |
155
+ | message | string | 否 | 回调消息 |
156
+ | signature | string | 否 | HMAC-SHA256签名(当任务设置了context.secret时必填) |
155
157
 
156
158
  ### 服务层 API
157
159
 
@@ -211,11 +213,23 @@ npm i --save @kne/fastify-task
211
213
 
212
214
  #### log - 记录日志
213
215
 
214
- | 参数名 | 类型 | 必填 | 说明 |
215
- |---------|--------|----|------|
216
- | taskId | string | 是 | 任务ID |
217
- | data | object | 否 | 日志数据 |
218
- | message | string | 否 | 日志消息 |
216
+ | 参数名 | 类型 | 必填 | 说明 |
217
+ |-----------|--------|----|----------------------------------------|
218
+ | id | string | 是 | 任务ID |
219
+ | taskId | string | 是 | 任务ID(id的别名) |
220
+ | data | object | 否 | 日志数据 |
221
+ | message | string | 否 | 日志消息 |
222
+ | signature | string | 否 | HMAC-SHA256签名(当任务设置了context.secret时必填) |
223
+
224
+ #### callback - 任务回调
225
+
226
+ | 参数名 | 类型 | 必填 | 说明 |
227
+ |-----------|--------|----|----------------------------------------|
228
+ | id | string | 是 | 任务ID |
229
+ | code | number | 是 | 状态码,0为成功 |
230
+ | data | object | 否 | 回调数据 |
231
+ | message | string | 否 | 回调消息 |
232
+ | signature | string | 否 | HMAC-SHA256签名(当任务设置了context.secret时必填) |
219
233
 
220
234
  #### runner - 执行系统任务
221
235
 
@@ -2,178 +2,274 @@ const fp = require('fastify-plugin');
2
2
 
3
3
  module.exports = fp(async (fastify, options) => {
4
4
  const { services } = fastify[options.name];
5
- fastify.get(`${options.prefix}/list`, {
6
- onRequest: options.getAuthenticate('read'), schema: {
7
- summary: '获取任务列表', query: {
8
- type: 'object', properties: {
9
- perPage: {
10
- type: 'number', default: 20
11
- }, currentPage: {
12
- type: 'number', default: 1
13
- }, filter: {
14
- type: 'object', properties: {
15
- id: {
16
- type: 'string'
17
- }, targetId: {
18
- type: 'string'
19
- }, targetName: {
20
- type: 'string'
21
- }, type: {
22
- type: 'string'
23
- }, status: {
24
- type: 'string'
25
- }, runnerType: {
26
- type: 'string'
27
- }, createdAt: {
28
- type: 'object', properties: {
29
- startTime: {
30
- type: 'string'
31
- }, endTime: {
32
- type: 'string'
33
- }
34
- }, description: 'createdAt区间查找'
35
- }, completedAt: {
36
- type: 'object', properties: {
37
- startTime: {
38
- type: 'string'
39
- }, endTime: {
40
- type: 'string'
41
- }
42
- }, description: 'completedAt区间查找'
5
+ fastify.get(
6
+ `${options.prefix}/list`,
7
+ {
8
+ onRequest: options.getAuthenticate('read'),
9
+ schema: {
10
+ summary: '获取任务列表',
11
+ query: {
12
+ type: 'object',
13
+ properties: {
14
+ perPage: {
15
+ type: 'number',
16
+ default: 20
17
+ },
18
+ currentPage: {
19
+ type: 'number',
20
+ default: 1
21
+ },
22
+ filter: {
23
+ type: 'object',
24
+ properties: {
25
+ id: {
26
+ type: 'string'
27
+ },
28
+ targetId: {
29
+ type: 'string'
30
+ },
31
+ targetName: {
32
+ type: 'string'
33
+ },
34
+ type: {
35
+ type: 'string'
36
+ },
37
+ status: {
38
+ type: 'string'
39
+ },
40
+ runnerType: {
41
+ type: 'string'
42
+ },
43
+ createdAt: {
44
+ type: 'object',
45
+ properties: {
46
+ startTime: {
47
+ type: 'string'
48
+ },
49
+ endTime: {
50
+ type: 'string'
51
+ }
52
+ },
53
+ description: 'createdAt区间查找'
54
+ },
55
+ completedAt: {
56
+ type: 'object',
57
+ properties: {
58
+ startTime: {
59
+ type: 'string'
60
+ },
61
+ endTime: {
62
+ type: 'string'
63
+ }
64
+ },
65
+ description: 'completedAt区间查找'
66
+ }
43
67
  }
68
+ },
69
+ sort: {
70
+ type: 'object',
71
+ description: '按completedAt、updatedAt字段排序,ASC为升序,DESC为降序'
44
72
  }
45
- }, sort: {
46
- type: 'object', description: '按completedAt、updatedAt字段排序,ASC为升序,DESC为降序'
47
73
  }
48
74
  }
49
75
  }
76
+ },
77
+ async request => {
78
+ return services.list(request.query);
50
79
  }
51
- }, async request => {
52
- return services.list(request.query);
53
- });
80
+ );
54
81
 
55
- fastify.post(`${options.prefix}/complete`, {
56
- onRequest: options.getAuthenticate('write'), schema: {
57
- summary: '手动完成任务', body: {
58
- type: 'object', properties: {
59
- id: {
60
- type: 'string'
61
- }, status: {
62
- type: 'string', enum: ['success', 'failed']
63
- }, error: {
64
- type: 'string'
65
- }, msg: {
66
- type: 'string'
67
- }, output: {
68
- type: 'object'
69
- }
70
- }, required: ['id', 'status']
82
+ fastify.post(
83
+ `${options.prefix}/complete`,
84
+ {
85
+ onRequest: options.getAuthenticate('write'),
86
+ schema: {
87
+ summary: '手动完成任务',
88
+ body: {
89
+ type: 'object',
90
+ properties: {
91
+ id: {
92
+ type: 'string'
93
+ },
94
+ status: {
95
+ type: 'string',
96
+ enum: ['success', 'failed']
97
+ },
98
+ error: {
99
+ type: 'string'
100
+ },
101
+ msg: {
102
+ type: 'string'
103
+ },
104
+ output: {
105
+ type: 'object'
106
+ }
107
+ },
108
+ required: ['id', 'status']
109
+ }
71
110
  }
111
+ },
112
+ async request => {
113
+ await services.complete(Object.assign({}, request.body, { userId: request.userInfo?.id }));
114
+ return {};
72
115
  }
73
- }, async request => {
74
- await services.complete(Object.assign({}, request.body, { userId: request.userInfo?.id }));
75
- return {};
76
- });
116
+ );
77
117
 
78
- fastify.post(`${options.prefix}/cancel`, {
79
- onRequest: options.getAuthenticate('write'), schema: {
80
- summary: '取消任务', body: {
81
- type: 'object', properties: {
82
- id: {
83
- type: 'string'
118
+ fastify.post(
119
+ `${options.prefix}/cancel`,
120
+ {
121
+ onRequest: options.getAuthenticate('write'),
122
+ schema: {
123
+ summary: '取消任务',
124
+ body: {
125
+ type: 'object',
126
+ properties: {
127
+ id: {
128
+ type: 'string'
129
+ }
84
130
  }
85
131
  }
86
132
  }
133
+ },
134
+ async request => {
135
+ await services.cancel(request.body);
136
+ return {};
87
137
  }
88
- }, async request => {
89
- await services.cancel(request.body);
90
- return {};
91
- });
138
+ );
92
139
 
93
- fastify.post(`${options.prefix}/retry`, {
94
- onRequest: options.getAuthenticate('write'), schema: {
95
- summary: '重试任务', body: {
96
- type: 'object', properties: {
97
- id: {
98
- type: 'string'
99
- }, taskIds: {
100
- type: 'array', items: {
140
+ fastify.post(
141
+ `${options.prefix}/retry`,
142
+ {
143
+ onRequest: options.getAuthenticate('write'),
144
+ schema: {
145
+ summary: '重试任务',
146
+ body: {
147
+ type: 'object',
148
+ properties: {
149
+ id: {
101
150
  type: 'string'
151
+ },
152
+ taskIds: {
153
+ type: 'array',
154
+ items: {
155
+ type: 'string'
156
+ }
102
157
  }
103
158
  }
104
159
  }
105
160
  }
161
+ },
162
+ async request => {
163
+ await services.retry(request.body);
164
+ return {};
106
165
  }
107
- }, async request => {
108
- await services.retry(request.body);
109
- return {};
110
- });
166
+ );
111
167
 
112
- fastify.post(`${options.prefix}/next`, {
113
- schema: {
114
- summary: '处理任务next', body: {
115
- type: 'object', properties: {
116
- id: {
117
- type: 'string', description: '任务ID'
118
- }, signature: {
119
- type: 'string', description: '签名'
120
- }, result: {
121
- type: 'string', description: '结果'
168
+ fastify.post(
169
+ `${options.prefix}/next`,
170
+ {
171
+ schema: {
172
+ summary: '处理任务next',
173
+ body: {
174
+ type: 'object',
175
+ properties: {
176
+ id: {
177
+ type: 'string',
178
+ description: '任务ID'
179
+ },
180
+ signature: {
181
+ type: 'string',
182
+ description: '签名'
183
+ },
184
+ result: {
185
+ type: 'string',
186
+ description: '结果'
187
+ }
122
188
  }
123
189
  }
124
190
  }
191
+ },
192
+ async request => {
193
+ return await services.processNext(request.body);
125
194
  }
126
- }, async request => {
127
- return await services.processNext(request.body);
128
- });
195
+ );
129
196
 
130
- fastify.post(`${options.prefix}/log`, {
131
- schema: {
132
- summary: '记录任务日志', body: {
133
- type: 'object', properties: {
134
- id: {
135
- type: 'string'
136
- }, data: {
137
- type: 'object'
138
- }, message: {
139
- type: 'string'
197
+ fastify.post(
198
+ `${options.prefix}/log`,
199
+ {
200
+ schema: {
201
+ summary: '记录任务日志',
202
+ body: {
203
+ type: 'object',
204
+ properties: {
205
+ id: {
206
+ type: 'string'
207
+ },
208
+ data: {
209
+ type: 'object'
210
+ },
211
+ message: {
212
+ type: 'string'
213
+ },
214
+ signature: {
215
+ type: 'string',
216
+ description: 'HMAC-SHA256签名'
217
+ }
140
218
  }
141
- }
142
- }, query: {
143
- type: 'object', properties: {
144
- taskId: {
145
- type: 'string'
219
+ },
220
+ query: {
221
+ type: 'object',
222
+ properties: {
223
+ taskId: {
224
+ type: 'string'
225
+ }
146
226
  }
147
227
  }
148
228
  }
229
+ },
230
+ async request => {
231
+ return await services.log(Object.assign({}, request.body, { taskId: request.query.taskId }));
149
232
  }
150
- }, async (request) => {
151
- return await services.log(Object.assign({}, request.body, { taskId: request.query.taskId }));
152
- });
233
+ );
153
234
 
154
- fastify.post(`${options.prefix}/callback`, {
155
- schema: {
156
- summary: '任务回调', body: {
157
- type: 'object', properties: {
158
- id: {
159
- type: 'string'
160
- }, code: {
161
- type: 'number'
162
- }, data: {
163
- type: 'object'
164
- }, message: {
165
- type: 'string'
235
+ fastify.post(
236
+ `${options.prefix}/callback`,
237
+ {
238
+ schema: {
239
+ summary: '任务回调',
240
+ body: {
241
+ type: 'object',
242
+ properties: {
243
+ id: {
244
+ type: 'string'
245
+ },
246
+ code: {
247
+ type: 'number'
248
+ },
249
+ data: {
250
+ type: 'object'
251
+ },
252
+ message: {
253
+ type: 'string'
254
+ },
255
+ signature: {
256
+ type: 'string',
257
+ description: 'HMAC-SHA256签名'
258
+ }
166
259
  }
167
- }
168
- }, query: {
169
- type: 'object', properties: {
170
- taskId: {
171
- type: 'string'
260
+ },
261
+ query: {
262
+ type: 'object',
263
+ properties: {
264
+ taskId: {
265
+ type: 'string'
266
+ }
172
267
  }
173
268
  }
174
269
  }
270
+ },
271
+ async request => {
272
+ return await services.callback(Object.assign({}, request.body, { taskId: request.query.taskId }));
175
273
  }
176
- }, async (request) => {
177
- return await services.callback(Object.assign({}, request.body, { taskId: request.query.taskId }));
178
- });
274
+ );
179
275
  });
@@ -1,21 +1,26 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const path = require('node:path');
3
3
  const fs = require('fs-extra');
4
+ const crypto = require('node:crypto');
4
5
 
5
6
  module.exports = fp(async (fastify, options) => {
6
7
  const { models } = fastify[options.name];
7
8
  const { Op } = fastify.sequelize.Sequelize;
8
- const create = async ({
9
- userId,
10
- input,
11
- type,
12
- targetId,
13
- targetType,
14
- runnerType,
15
- delay,
16
- scriptName,
17
- options: currentOptions
18
- }) => {
9
+
10
+ const generateSignature = ({ secret, id, data }) => {
11
+ const dataToSign = `${id}|${typeof data === 'string' ? data : JSON.stringify(data)}`;
12
+ const hmac = crypto.createHmac('sha256', secret);
13
+ hmac.update(dataToSign);
14
+ return hmac.digest('hex');
15
+ };
16
+
17
+ const verifySignature = ({ secret, id, data, signature }) => {
18
+ if (!secret) return true;
19
+ const expectedSignature = generateSignature({ secret, id, data });
20
+ return signature === expectedSignature;
21
+ };
22
+
23
+ const create = async ({ userId, input, type, targetId, targetType, runnerType, delay, scriptName, options: currentOptions }) => {
19
24
  if (typeof options.task[type] !== 'function') {
20
25
  throw new Error('未找到合法的任务声明');
21
26
  }
@@ -33,13 +38,16 @@ module.exports = fp(async (fastify, options) => {
33
38
  };
34
39
 
35
40
  const resetAll = async () => {
36
- await models.task.update({
37
- status: 'pending'
38
- }, {
39
- where: {
40
- status: 'running'
41
+ await models.task.update(
42
+ {
43
+ status: 'pending'
44
+ },
45
+ {
46
+ where: {
47
+ status: 'running'
48
+ }
41
49
  }
42
- });
50
+ );
43
51
  };
44
52
 
45
53
  const executor = async ({ type, scriptName, ...props }) => {
@@ -48,11 +56,14 @@ module.exports = fp(async (fastify, options) => {
48
56
  throw new Error(`未匹配到任务执行器:${taskModulePath}`);
49
57
  }
50
58
  return await require(taskModulePath)(fastify, options, {
51
- ...props, updateProgress: async progress => {
52
- typeof props?.task?.update === 'function' && (await props.task.update({
53
- progress: progress
54
- }));
55
- }, polling: async (callback, currentOptions) => {
59
+ ...props,
60
+ updateProgress: async progress => {
61
+ typeof props?.task?.update === 'function' &&
62
+ (await props.task.update({
63
+ progress: progress
64
+ }));
65
+ },
66
+ polling: async (callback, currentOptions) => {
56
67
  let pollCount = 0;
57
68
  const maxPollTimes = currentOptions?.maxPollTimes || options.maxPollTimes;
58
69
  const pollInterval = currentOptions?.pollInterval || options.pollInterval;
@@ -70,10 +81,16 @@ module.exports = fp(async (fastify, options) => {
70
81
 
71
82
  if (typeof props?.task?.update === 'function') {
72
83
  await props.task.reload();
73
- await props.task.update(Object.assign({}, {
74
- pollCount: props.task.pollCount + 1,
75
- pollResults: [...props.task.pollResults, Object.assign({}, pollingResult, { time: new Date() })]
76
- }, Number.isInteger(progress) ? { progress } : {}));
84
+ await props.task.update(
85
+ Object.assign(
86
+ {},
87
+ {
88
+ pollCount: props.task.pollCount + 1,
89
+ pollResults: [...props.task.pollResults, Object.assign({}, pollingResult, { time: new Date() })]
90
+ },
91
+ Number.isInteger(progress) ? { progress } : {}
92
+ )
93
+ );
77
94
  }
78
95
 
79
96
  if (result === 'failed') {
@@ -95,7 +112,8 @@ module.exports = fp(async (fastify, options) => {
95
112
  // 开始第一次轮询
96
113
  setTimeout(executePolling, pollInterval);
97
114
  });
98
- }, next: async context => {
115
+ },
116
+ next: async context => {
99
117
  if (typeof props?.task?.update === 'function') {
100
118
  await props.task.update({ context, status: 'waiting' });
101
119
  }
@@ -109,25 +127,24 @@ module.exports = fp(async (fastify, options) => {
109
127
  if (task.status !== 'waiting') {
110
128
  throw new Error('当前任务状态不允许执行Next操作');
111
129
  }
112
- if (task.context?.secret) {
113
- const dataToSign = `${id}|${resultStr}`;
114
- // 使用 HMAC-SHA256 生成签名
115
- const hmac = crypto.createHmac('sha256', task.context.secret);
116
- hmac.update(dataToSign);
117
- if (signature !== hmac.digest('hex')) {
118
- throw new Error('签名验证失败');
119
- }
130
+ if (task.context?.secret && !verifySignature({ secret: task.context.secret, id, data: resultStr, signature })) {
131
+ throw new Error('签名验证失败');
120
132
  }
121
133
  const result = JSON.parse(resultStr);
122
134
  if (result.code !== 0) {
123
135
  await task.update({
124
- status: 'failed', error: result, completedAt: new Date()
136
+ status: 'failed',
137
+ error: result,
138
+ completedAt: new Date()
125
139
  });
126
140
  return;
127
141
  }
128
142
  await options.task[task.type]({ task, result: result.data, context: task.context });
129
143
  await task.update({
130
- status: 'success', output: result, progress: 100, completedAt: new Date()
144
+ status: 'success',
145
+ output: result,
146
+ progress: 100,
147
+ completedAt: new Date()
131
148
  });
132
149
  };
133
150
 
@@ -143,7 +160,7 @@ module.exports = fp(async (fastify, options) => {
143
160
  completedAt: null,
144
161
  context: {}
145
162
  });
146
- const addLog = (props) => {
163
+ const addLog = props => {
147
164
  return log(Object.assign({}, props, { taskId: task.id }));
148
165
  };
149
166
  executor({ type: task.type, scriptName: task.scriptName, task, log: addLog })
@@ -153,17 +170,24 @@ module.exports = fp(async (fastify, options) => {
153
170
  }
154
171
  await options.task[task.type]({ task, result, context: task.context });
155
172
  await task.update({
156
- status: 'success', output: result, progress: 100, completedAt: new Date()
173
+ status: 'success',
174
+ output: result,
175
+ progress: 100,
176
+ completedAt: new Date()
157
177
  });
158
178
  })
159
179
  .catch(e => {
160
180
  return task.update({
161
- status: 'failed', error: (e.stack || '').replaceAll(process.cwd(), '/server'), completedAt: new Date()
181
+ status: 'failed',
182
+ error: (e.stack || '').replaceAll(process.cwd(), '/server'),
183
+ completedAt: new Date()
162
184
  });
163
185
  });
164
186
  } catch (e) {
165
187
  await task.update({
166
- status: 'failed', error: (e.stack || '').replaceAll(process.cwd(), '/server'), completedAt: new Date()
188
+ status: 'failed',
189
+ error: (e.stack || '').replaceAll(process.cwd(), '/server'),
190
+ completedAt: new Date()
167
191
  });
168
192
  }
169
193
  };
@@ -171,7 +195,8 @@ module.exports = fp(async (fastify, options) => {
171
195
  const runner = async () => {
172
196
  const runningTaskCount = await models.task.count({
173
197
  where: {
174
- runnerType: 'system', status: 'running'
198
+ runnerType: 'system',
199
+ status: 'running'
175
200
  }
176
201
  });
177
202
  const limit = options.limit - runningTaskCount;
@@ -181,15 +206,19 @@ module.exports = fp(async (fastify, options) => {
181
206
  }
182
207
  const pendingTasks = await models.task.findAll({
183
208
  where: {
184
- runnerType: 'system', status: 'pending', startTime: {
209
+ runnerType: 'system',
210
+ status: 'pending',
211
+ startTime: {
185
212
  [Op.lte]: new Date()
186
213
  }
187
- }, limit: options.limit
214
+ },
215
+ limit: options.limit
188
216
  });
189
217
 
190
218
  const count = await models.task.count({
191
219
  where: {
192
- runnerType: 'system', status: 'pending'
220
+ runnerType: 'system',
221
+ status: 'pending'
193
222
  }
194
223
  });
195
224
 
@@ -209,15 +238,21 @@ module.exports = fp(async (fastify, options) => {
209
238
 
210
239
  const cancel = async ({ id, targetId, targetType, type }) => {
211
240
  if (targetId && targetType && type) {
212
- return await models.task.update({
213
- status: 'canceled'
214
- }, {
215
- where: {
216
- targetId, targetType, type, status: {
217
- [Op.in]: ['pending', 'running']
241
+ return await models.task.update(
242
+ {
243
+ status: 'canceled'
244
+ },
245
+ {
246
+ where: {
247
+ targetId,
248
+ targetType,
249
+ type,
250
+ status: {
251
+ [Op.in]: ['pending', 'running']
252
+ }
218
253
  }
219
254
  }
220
- });
255
+ );
221
256
  }
222
257
  if (id) {
223
258
  const task = await detail({ id });
@@ -239,18 +274,31 @@ module.exports = fp(async (fastify, options) => {
239
274
  try {
240
275
  await options.task[task.type]({ task, result: output });
241
276
  await task.update({
242
- status: 'success', output, progress: 100, completedAt: new Date(), completedUserId: userId
277
+ status: 'success',
278
+ output,
279
+ progress: 100,
280
+ completedAt: new Date(),
281
+ completedUserId: userId
243
282
  });
244
283
  } catch (e) {
245
- await task.update(Object.assign({}, props, {
246
- status: 'failed', output, error: (e.stack || '').replaceAll(process.cwd(), '/server'), completedAt: new Date()
247
- }));
284
+ await task.update(
285
+ Object.assign({}, props, {
286
+ status: 'failed',
287
+ output,
288
+ error: (e.stack || '').replaceAll(process.cwd(), '/server'),
289
+ completedAt: new Date()
290
+ })
291
+ );
248
292
  throw e;
249
293
  }
250
294
  } else {
251
- await task.update(Object.assign({}, props, {
252
- status: 'failed', completedAt: new Date(), completedUserId: userId
253
- }));
295
+ await task.update(
296
+ Object.assign({}, props, {
297
+ status: 'failed',
298
+ completedAt: new Date(),
299
+ completedUserId: userId
300
+ })
301
+ );
254
302
  }
255
303
  };
256
304
 
@@ -363,7 +411,8 @@ module.exports = fp(async (fastify, options) => {
363
411
  });
364
412
 
365
413
  return {
366
- pageData: rows, totalCount: count
414
+ pageData: rows,
415
+ totalCount: count
367
416
  };
368
417
  };
369
418
 
@@ -373,7 +422,9 @@ module.exports = fp(async (fastify, options) => {
373
422
  throw new Error('只有失败或取消的任务允许重试');
374
423
  }
375
424
  await task.update({
376
- status: 'pending', completedAt: null, completedUserId: null
425
+ status: 'pending',
426
+ completedAt: null,
427
+ completedUserId: null
377
428
  });
378
429
  };
379
430
 
@@ -388,36 +439,66 @@ module.exports = fp(async (fastify, options) => {
388
439
  }
389
440
  };
390
441
 
391
- const log = async ({ taskId, data, message = '' }) => {
392
- const task = await detail({ id: taskId });
442
+ const log = async ({ id, taskId, data, message = '', signature }) => {
443
+ const targetId = id || taskId;
444
+ const task = await detail({ id: targetId });
393
445
  if (!task) {
394
446
  throw new Error('任务不存在');
395
447
  }
396
448
 
449
+ if (task.context?.secret && !verifySignature({ secret: task.context.secret, id: targetId, data: { data, message }, signature })) {
450
+ throw new Error('签名验证失败');
451
+ }
452
+
397
453
  const currentOptions = task.options || {};
398
454
  const logs = (currentOptions.logs || []).slice(0);
399
455
  logs.splice(0, 0, {
400
- data, message, time: new Date()
456
+ data,
457
+ message,
458
+ time: new Date()
401
459
  });
402
460
  if (logs.length > 100) {
403
461
  logs.splice(0, logs.length - 100);
404
462
  }
405
463
  await task.update({
406
464
  options: {
407
- ...currentOptions, logs
465
+ ...currentOptions,
466
+ logs
408
467
  }
409
468
  });
410
469
 
411
470
  return task;
412
471
  };
413
472
 
414
- const callback = async (id, result) => {
415
- await log({ id, message: '回调结果', data: JSON.stringify(result) });
416
- const input = Object.assign({}, { id }, result.code === 0 ? {
417
- status: 'success', output: result.data
418
- } : {
419
- status: 'failed', output: result.data, error: result.message
420
- });
473
+ const callback = async ({ id, code, data, message, signature }) => {
474
+ const task = await detail({ id });
475
+ if (!task) {
476
+ throw new Error('任务不存在');
477
+ }
478
+
479
+ if (task.context?.secret && !verifySignature({ secret: task.context.secret, id, data: { code, data, message }, signature })) {
480
+ throw new Error('签名验证失败');
481
+ }
482
+
483
+ const result = { code, data, message };
484
+ const logData = JSON.stringify(result);
485
+ const logMessage = '回调结果';
486
+ const logSignature = task.context?.secret ? generateSignature({ secret: task.context.secret, id, data: { data: logData, message: logMessage } }) : undefined;
487
+ await log({ taskId: id, message: logMessage, data: logData, signature: logSignature });
488
+ const input = Object.assign(
489
+ {},
490
+ { id },
491
+ code === 0
492
+ ? {
493
+ status: 'success',
494
+ output: data
495
+ }
496
+ : {
497
+ status: 'failed',
498
+ output: data,
499
+ error: message
500
+ }
501
+ );
421
502
  await complete(input);
422
503
  };
423
504
 
@@ -437,4 +518,4 @@ module.exports = fp(async (fastify, options) => {
437
518
  processSystemTask,
438
519
  waitingComplete
439
520
  });
440
- });
521
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-task",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "一个 Fastify 插件,用于任务编排、追踪任务执行状态和结果。支持系统自动执行和手动执行两种模式,提供完整的任务生命周期管理",
5
5
  "main": "index.js",
6
6
  "scripts": {