@kne/fastify-task 1.0.9 → 1.1.0

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
@@ -1,11 +1,8 @@
1
-
2
1
  # fastify-task
3
2
 
4
-
5
3
  ### 描述
6
4
 
7
- 用于编排任务,追踪任务执行状态,结果
8
-
5
+ 一个 Fastify 插件,用于任务编排、追踪任务执行状态和结果。支持系统自动执行和手动执行两种模式,提供完整的任务生命周期管理
9
6
 
10
7
  ### 安装
11
8
 
@@ -13,15 +10,250 @@
13
10
  npm i --save @kne/fastify-task
14
11
  ```
15
12
 
16
- ### 示例
13
+ ### 概述
14
+
15
+ @kne/fastify-task 是一个 Fastify 插件,用于任务编排、追踪任务执行状态和结果。支持系统自动执行和手动执行两种模式,提供完整的任务生命周期管理。
16
+
17
+ ### 主要特性
18
+
19
+ - **任务创建与管理**:支持创建、取消、重试、完成任务
20
+ - **多种执行模式**:支持系统自动执行(system)和手动执行(manual)
21
+ - **定时任务调度**:基于 cron 表达式的定时任务执行
22
+ - **任务状态追踪**:实时追踪任务进度、轮询结果
23
+ - **异步回调支持**:支持外部系统回调通知任务完成
24
+ - **日志记录**:支持任务执行日志记录,最多保留100条
25
+
26
+ ### 使用场景
17
27
 
18
- #### 示例代码
28
+ - 文档导出、数据迁移等异步处理任务
29
+ - 第三方 API 调用后异步回调处理
30
+ - 定时批量数据处理
31
+ - 需要追踪进度和状态的长时任务
19
32
 
33
+ ### 任务状态流转
20
34
 
35
+ | 状态 | 说明 |
36
+ |----------|--------|
37
+ | pending | 待执行 |
38
+ | running | 执行中 |
39
+ | waiting | 等待外部回调 |
40
+ | success | 执行成功 |
41
+ | failed | 执行失败 |
42
+ | canceled | 已取消 |
43
+
44
+ ### 示例
21
45
 
22
46
  ### API
23
47
 
24
- | 属性名 | 说明 | 类型 | 默认值 |
25
- |-----|----|----|-----|
26
- | | | | |
48
+ ### 插件配置
49
+
50
+ | 属性名 | 类型 | 默认值 | 说明 |
51
+ |-------------------|----------|----------------|----------------------|
52
+ | dbTableNamePrefix | string | 't_' | 数据库表名前缀 |
53
+ | prefix | string | '/api/task' | API 路由前缀 |
54
+ | name | string | 'task' | 命名空间名称 |
55
+ | limit | number | 10 | 并发执行任务数上限 |
56
+ | dir | string | 'libs/tasks' | 任务脚本目录 |
57
+ | cronTime | string | '*/10 * * * *' | cron 执行周期,设为 null 禁用 |
58
+ | scriptName | string | 'index' | 默认任务脚本名称 |
59
+ | maxPollTimes | number | 20 | 最大轮询次数 |
60
+ | pollInterval | number | 10000 | 轮询间隔(毫秒) |
61
+ | getUserModel | function | - | 获取用户模型的函数 |
62
+ | getAuthenticate | function | - | 获取认证中间件的函数 |
63
+ | task | object | {} | 任务类型处理函数映射 |
64
+
65
+ ### HTTP API
66
+
67
+ #### 获取任务列表
68
+
69
+ **GET** `{prefix}/list`
70
+
71
+ | 参数名 | 类型 | 默认值 | 说明 |
72
+ |------------------------------|--------|-----|------------|
73
+ | perPage | number | 20 | 每页数量 |
74
+ | currentPage | number | 1 | 当前页码 |
75
+ | filter.id | string | - | 任务ID |
76
+ | filter.targetId | string | - | 目标对象ID |
77
+ | filter.targetName | string | - | 目标名称(模糊匹配) |
78
+ | filter.type | string | - | 任务类型 |
79
+ | filter.status | string | - | 任务状态 |
80
+ | filter.runnerType | string | - | 执行者类型 |
81
+ | filter.createdAt.startTime | string | - | 创建时间起始 |
82
+ | filter.createdAt.endTime | string | - | 创建时间结束 |
83
+ | filter.completedAt.startTime | string | - | 完成时间起始 |
84
+ | filter.completedAt.endTime | string | - | 完成时间结束 |
85
+ | sort | object | - | 排序规则 |
86
+
87
+ **返回值**
88
+
89
+ | 属性名 | 类型 | 说明 |
90
+ |------------|--------|------|
91
+ | pageData | array | 任务列表 |
92
+ | totalCount | number | 总数量 |
93
+
94
+ #### 手动完成任务
95
+
96
+ **POST** `{prefix}/complete`
97
+
98
+ | 参数名 | 类型 | 必填 | 说明 |
99
+ |--------|--------|----|-------------------|
100
+ | id | string | 是 | 任务ID |
101
+ | status | string | 是 | 状态:success/failed |
102
+ | error | string | 否 | 错误信息 |
103
+ | msg | string | 否 | 消息 |
104
+ | output | object | 否 | 输出数据 |
105
+
106
+ #### 取消任务
107
+
108
+ **POST** `{prefix}/cancel`
109
+
110
+ | 参数名 | 类型 | 必填 | 说明 |
111
+ |-----|--------|----|------|
112
+ | id | string | 是 | 任务ID |
113
+
114
+ #### 重试任务
115
+
116
+ **POST** `{prefix}/retry`
117
+
118
+ | 参数名 | 类型 | 必填 | 说明 |
119
+ |---------|----------|----|--------|
120
+ | id | string | 否 | 单个任务ID |
121
+ | taskIds | string[] | 否 | 任务ID数组 |
122
+
123
+ #### 处理任务 Next
124
+
125
+ **POST** `{prefix}/next`
126
+
127
+ | 参数名 | 类型 | 必填 | 说明 |
128
+ |-----------|--------|----|---------------|
129
+ | id | string | 是 | 任务ID |
130
+ | signature | string | 否 | HMAC-SHA256签名 |
131
+ | result | string | 是 | JSON格式的结果 |
132
+
133
+ #### 记录任务日志
134
+
135
+ **POST** `{prefix}/log`
136
+
137
+ | 参数名 | 类型 | 必填 | 说明 |
138
+ |---------|--------|----|-------------|
139
+ | id | string | 是 | 任务ID(body) |
140
+ | taskId | string | 是 | 任务ID(query) |
141
+ | data | object | 否 | 日志数据 |
142
+ | message | string | 否 | 日志消息 |
143
+
144
+ #### 任务回调
145
+
146
+ **POST** `{prefix}/callback`
147
+
148
+ | 参数名 | 类型 | 必填 | 说明 |
149
+ |---------|--------|----|-------------|
150
+ | id | string | 是 | 任务ID(body) |
151
+ | taskId | string | 是 | 任务ID(query) |
152
+ | code | number | 是 | 状态码,0为成功 |
153
+ | data | object | 否 | 回调数据 |
154
+ | message | string | 否 | 回调消息 |
155
+
156
+ ### 服务层 API
157
+
158
+ #### create - 创建任务
159
+
160
+ | 参数名 | 类型 | 必填 | 说明 |
161
+ |------------|--------|----|---------------------|
162
+ | userId | string | 否 | 用户ID |
163
+ | input | object | 否 | 输入数据 |
164
+ | type | string | 是 | 任务类型 |
165
+ | targetId | string | 是 | 目标对象ID |
166
+ | targetType | string | 是 | 目标对象类型 |
167
+ | runnerType | string | 否 | 执行者类型:manual/system |
168
+ | delay | number | 否 | 延迟执行秒数 |
169
+ | scriptName | string | 否 | 脚本名称 |
170
+ | options | object | 否 | 扩展选项 |
171
+
172
+ **返回值**:Task 实例
173
+
174
+ #### detail - 获取任务详情
175
+
176
+ | 参数名 | 类型 | 必填 | 说明 |
177
+ |-----|--------|----|------|
178
+ | id | string | 是 | 任务ID |
179
+
180
+ **返回值**:Task 实例
181
+
182
+ #### list - 获取任务列表
183
+
184
+ 同 HTTP API list 接口参数
185
+
186
+ #### complete - 完成任务
187
+
188
+ | 参数名 | 类型 | 必填 | 说明 |
189
+ |--------|--------|----|-------------------|
190
+ | id | string | 是 | 任务ID |
191
+ | userId | string | 否 | 完成人ID |
192
+ | output | object | 否 | 输出数据 |
193
+ | status | string | 是 | 状态:success/failed |
194
+ | error | string | 否 | 错误信息 |
195
+
196
+ #### cancel - 取消任务
197
+
198
+ | 参数名 | 类型 | 必填 | 说明 |
199
+ |------------|--------|----|--------------|
200
+ | id | string | 否 | 任务ID |
201
+ | targetId | string | 否 | 目标对象ID(批量取消) |
202
+ | targetType | string | 否 | 目标对象类型(批量取消) |
203
+ | type | string | 否 | 任务类型(批量取消) |
204
+
205
+ #### retry - 重试任务
206
+
207
+ | 参数名 | 类型 | 必填 | 说明 |
208
+ |---------|----------|----|--------|
209
+ | id | string | 否 | 单个任务ID |
210
+ | taskIds | string[] | 否 | 任务ID数组 |
211
+
212
+ #### log - 记录日志
213
+
214
+ | 参数名 | 类型 | 必填 | 说明 |
215
+ |---------|--------|----|------|
216
+ | taskId | string | 是 | 任务ID |
217
+ | data | object | 否 | 日志数据 |
218
+ | message | string | 否 | 日志消息 |
219
+
220
+ #### runner - 执行系统任务
221
+
222
+ 无参数,由 cron 定时调用
223
+
224
+ #### resetAll - 重置所有运行中任务
225
+
226
+ 无参数,将所有 running 状态任务重置为 pending
227
+
228
+ #### waitingComplete - 等待任务完成
229
+
230
+ | 参数名 | 类型 | 默认值 | 说明 |
231
+ |--------------|--------|------|----------|
232
+ | id | string | - | 任务ID |
233
+ | pollInterval | number | 1000 | 轮询间隔(毫秒) |
234
+ | maxPollTimes | number | 20 | 最大轮询次数 |
235
+
236
+ **返回值**:任务输出数据
237
+
238
+ ### 任务模型字段
27
239
 
240
+ | 属性名 | 类型 | 说明 |
241
+ |-------------|--------|---------------------|
242
+ | id | string | 任务ID |
243
+ | type | string | 任务类型 |
244
+ | scriptName | string | 脚本名称 |
245
+ | targetId | string | 目标对象ID |
246
+ | targetType | string | 目标对象类型 |
247
+ | runnerType | enum | 执行者类型:manual/system |
248
+ | startTime | date | 最早执行时间 |
249
+ | completedAt | date | 完成时间 |
250
+ | input | json | 输入数据 |
251
+ | output | json | 输出数据 |
252
+ | error | json | 错误信息 |
253
+ | status | enum | 任务状态 |
254
+ | context | json | 上下文信息 |
255
+ | pollResults | json | 轮询结果记录 |
256
+ | pollCount | number | 轮询次数 |
257
+ | progress | number | 进度(0-100) |
258
+ | msg | text | 消息 |
259
+ | options | json | 扩展选项 |
@@ -2,195 +2,178 @@ 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(
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
- }
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区间查找'
67
43
  }
68
- },
69
- sort: {
70
- type: 'object',
71
- description: '按completedAt、updatedAt字段排序,ASC为升序,DESC为降序'
72
44
  }
45
+ }, sort: {
46
+ type: 'object', description: '按completedAt、updatedAt字段排序,ASC为升序,DESC为降序'
73
47
  }
74
48
  }
75
49
  }
76
- },
77
- async request => {
78
- return services.list(request.query);
79
50
  }
80
- );
51
+ }, async request => {
52
+ return services.list(request.query);
53
+ });
81
54
 
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']
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']
71
+ }
72
+ }
73
+ }, async request => {
74
+ await services.complete(Object.assign({}, request.body, { userId: request.userInfo?.id }));
75
+ return {};
76
+ });
77
+
78
+ fastify.post(`${options.prefix}/cancel`, {
79
+ onRequest: options.getAuthenticate('write'), schema: {
80
+ summary: '取消任务', body: {
81
+ type: 'object', properties: {
82
+ id: {
83
+ type: 'string'
84
+ }
109
85
  }
110
86
  }
111
- },
112
- async request => {
113
- await services.complete(Object.assign({}, request.body, { userId: request.userInfo?.id }));
114
- return {};
115
87
  }
116
- );
88
+ }, async request => {
89
+ await services.cancel(request.body);
90
+ return {};
91
+ });
117
92
 
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: {
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: {
128
101
  type: 'string'
129
102
  }
130
103
  }
131
104
  }
132
105
  }
133
- },
134
- async request => {
135
- await services.cancel(request.body);
136
- return {};
137
106
  }
138
- );
107
+ }, async request => {
108
+ await services.retry(request.body);
109
+ return {};
110
+ });
139
111
 
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: {
150
- type: 'string'
151
- },
152
- taskIds: {
153
- type: 'array',
154
- items: {
155
- type: 'string'
156
- }
157
- }
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: '结果'
158
122
  }
159
123
  }
160
124
  }
161
- },
162
- async request => {
163
- await services.retry(request.body);
164
- return {};
165
125
  }
166
- );
126
+ }, async request => {
127
+ return await services.processNext(request.body);
128
+ });
167
129
 
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
- }
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'
140
+ }
141
+ }
142
+ }, query: {
143
+ type: 'object', properties: {
144
+ taskId: {
145
+ type: 'string'
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }, async (request) => {
151
+ return await services.log(Object.assign({}, request.body, { taskId: request.query.taskId }));
152
+ });
153
+
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'
166
+ }
167
+ }
168
+ }, query: {
169
+ type: 'object', properties: {
170
+ taskId: {
171
+ type: 'string'
188
172
  }
189
173
  }
190
174
  }
191
- },
192
- async request => {
193
- return await services.processNext(request.body);
194
175
  }
195
- );
176
+ }, async (request) => {
177
+ return await services.callback(Object.assign({}, request.body, { taskId: request.query.taskId }));
178
+ });
196
179
  });
@@ -395,11 +395,13 @@ module.exports = fp(async (fastify, options) => {
395
395
  }
396
396
 
397
397
  const currentOptions = task.options || {};
398
- const logs = currentOptions.logs || [];
399
- logs.push({
398
+ const logs = (currentOptions.logs || []).slice(0);
399
+ logs.splice(0, 0, {
400
400
  data, message, time: new Date()
401
401
  });
402
-
402
+ if (logs.length > 100) {
403
+ logs.splice(0, logs.length - 100);
404
+ }
403
405
  await task.update({
404
406
  options: {
405
407
  ...currentOptions, logs
@@ -409,6 +411,16 @@ module.exports = fp(async (fastify, options) => {
409
411
  return task;
410
412
  };
411
413
 
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
+ });
421
+ await complete(input);
422
+ };
423
+
412
424
  Object.assign(fastify[options.name].services, {
413
425
  create,
414
426
  detail,
@@ -419,6 +431,7 @@ module.exports = fp(async (fastify, options) => {
419
431
  resetAll,
420
432
  retry,
421
433
  log,
434
+ callback,
422
435
  executor,
423
436
  processNext,
424
437
  processSystemTask,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kne/fastify-task",
3
- "version": "1.0.9",
4
- "description": "用于编排任务,追踪任务执行状态,结果",
3
+ "version": "1.1.0",
4
+ "description": "一个 Fastify 插件,用于任务编排、追踪任务执行状态和结果。支持系统自动执行和手动执行两种模式,提供完整的任务生命周期管理",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "init": "husky",
@@ -10,7 +10,9 @@
10
10
  "build:md": "npx @kne/md-doc",
11
11
  "start:md": "npx @kne/md-doc --watch",
12
12
  "prettier": "prettier --config .prettierrc --write '{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}'",
13
- "lint-staged": "npx lint-staged"
13
+ "lint-staged": "npx lint-staged",
14
+ "test": "mocha test/**/*.test.js",
15
+ "test:coverage": "nyc --reporter=html --reporter=text mocha test/**/*.test.js"
14
16
  },
15
17
  "lint-staged": {
16
18
  "{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}": [
@@ -40,12 +42,17 @@
40
42
  },
41
43
  "devDependencies": {
42
44
  "@fastify/env": "^5.0.2",
45
+ "@kne/fastify-namespace": "*",
43
46
  "@kne/fastify-sequelize": "^3.0.6",
47
+ "chai": "^6.2.2",
44
48
  "fastify": "^5.4.0",
45
49
  "fastify-plugin": "^5.0.1",
46
50
  "husky": "^9.0.11",
51
+ "mocha": "^11.7.5",
47
52
  "nodemon": "^3.1.3",
53
+ "nyc": "^17.1.0",
48
54
  "prettier": "^3.2.5",
55
+ "sinon": "^21.0.0",
49
56
  "sqlite3": "^5.1.7"
50
57
  },
51
58
  "dependencies": {