@kne/fastify-task 3.0.0-alpha.8 → 3.0.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 +1 -5
- package/libs/controllers/main.js +122 -63
- package/libs/controllers/statistics.js +11 -2
- package/libs/helpers/task-service-context.js +12 -4
- package/libs/models/task.js +0 -4
- package/libs/schema/response.js +74 -0
- package/libs/services/statistics.js +121 -34
- package/libs/services/task.js +75 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -504,7 +504,6 @@ const signature = generateSignature({
|
|
|
504
504
|
| type | string | 是 | - | 任务类型,必须已在主项目或 `append` 中声明 |
|
|
505
505
|
| targetId | string | 是 | - | 目标对象ID |
|
|
506
506
|
| targetType | string | 是 | - | 目标对象类型 |
|
|
507
|
-
| targetName | string | 否 | - | 目标对象名称 |
|
|
508
507
|
| input | object | 否 | - | 输入数据 |
|
|
509
508
|
| runnerType | string | 否 | - | 执行者类型:`manual` / `system` |
|
|
510
509
|
| delay | number | 否 | `0` | 延迟执行秒数 |
|
|
@@ -533,7 +532,6 @@ const signature = generateSignature({
|
|
|
533
532
|
| currentPage | number | 否 | `1` | 当前页码 |
|
|
534
533
|
| filter.id | string | 否 | - | 任务ID |
|
|
535
534
|
| filter.targetId | string | 否 | - | 目标对象ID |
|
|
536
|
-
| filter.targetName | string | 否 | - | 目标名称(模糊匹配 `input.name`) |
|
|
537
535
|
| filter.type | string | 否 | - | 任务类型 |
|
|
538
536
|
| filter.status | string | 否 | - | 任务状态 |
|
|
539
537
|
| filter.runnerType | string | 否 | - | 执行者类型 |
|
|
@@ -710,7 +708,7 @@ SSE 实时推送任务统计数据,需 `statistics` 权限。
|
|
|
710
708
|
|
|
711
709
|
| 方法签名 | 说明 |
|
|
712
710
|
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------|
|
|
713
|
-
| `services.create({ userId, input, type, targetId, targetType,
|
|
711
|
+
| `services.create({ userId, input, type, targetId, targetType, runnerType, delay, scriptName, priority, parentTaskId, maxRetries, timeout, context, options })` | 创建任务,返回 Task 实例 |
|
|
714
712
|
| `services.detail({ id })` | 获取任务详情,返回 Task 实例 |
|
|
715
713
|
| `services.list({ filter, perPage, currentPage, sort })` | 获取任务列表,返回 `{ pageData, totalCount }` |
|
|
716
714
|
| `services.complete({ id, userId, status, output, error })` | 手动完成任务 |
|
|
@@ -727,7 +725,6 @@ SSE 实时推送任务统计数据,需 `statistics` 权限。
|
|
|
727
725
|
| type | string | 是 | - | 任务类型 |
|
|
728
726
|
| targetId | string | 是 | - | 目标对象ID |
|
|
729
727
|
| targetType | string | 是 | - | 目标对象类型 |
|
|
730
|
-
| targetName | string | 否 | - | 目标对象名称 |
|
|
731
728
|
| runnerType | string | 否 | - | 执行者类型 |
|
|
732
729
|
| delay | number | 否 | `0` | 延迟执行秒数 |
|
|
733
730
|
| scriptName | string | 否 | - | 脚本名称 |
|
|
@@ -825,7 +822,6 @@ SSE 实时推送任务统计数据,需 `statistics` 权限。
|
|
|
825
822
|
| scriptName | string | 任务脚本名称 |
|
|
826
823
|
| targetId | string | 任务目标对象ID |
|
|
827
824
|
| targetType | string | 任务目标对象类型 |
|
|
828
|
-
| targetName | string | 任务目标对象名称 |
|
|
829
825
|
| runnerType | string | 执行者类型:`manual` / `system`,默认 `manual` |
|
|
830
826
|
| priority | number | 任务优先级,数值越大越优先,默认 0 |
|
|
831
827
|
| parentTaskId | string | 父任务ID,用于任务依赖 |
|
package/libs/controllers/main.js
CHANGED
|
@@ -1,4 +1,23 @@
|
|
|
1
1
|
const fp = require('fastify-plugin');
|
|
2
|
+
const { any, success, empty, TASK_STATUS, RUNNER_TYPE, task, taskList } = require('../schema/response');
|
|
3
|
+
|
|
4
|
+
const TAG = '任务-任务管理';
|
|
5
|
+
const CALLBACK_TAG = '任务-外部回调';
|
|
6
|
+
const SIGNATURE_HINT = '任务 context.secret 存在时校验 HMAC-SHA256 签名(密钥为 secret,内容为 `${id}|${JSON 数据}`),不通过报错;未设置 secret 时不校验';
|
|
7
|
+
const timeRange = name => ({
|
|
8
|
+
type: 'object',
|
|
9
|
+
properties: {
|
|
10
|
+
startTime: {
|
|
11
|
+
type: 'string',
|
|
12
|
+
description: `${name}起始时间(含),可被 Date 解析的时间字符串`
|
|
13
|
+
},
|
|
14
|
+
endTime: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
description: `${name}结束时间(含),可被 Date 解析的时间字符串`
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
description: `${name}区间查找`
|
|
20
|
+
});
|
|
2
21
|
|
|
3
22
|
module.exports = fp(async (fastify, options) => {
|
|
4
23
|
const { services } = fastify[options.name];
|
|
@@ -8,7 +27,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
8
27
|
{
|
|
9
28
|
onRequest: options.getAuthenticate('write'),
|
|
10
29
|
schema: {
|
|
30
|
+
tags: [TAG],
|
|
11
31
|
summary: '创建任务',
|
|
32
|
+
description: '创建一条 pending 状态的任务,到达开始时间后由定时器按优先级调度执行(system)或等待人工完成(manual);type 必须是已注册的任务类型,返回新任务 ID',
|
|
12
33
|
body: {
|
|
13
34
|
type: 'object',
|
|
14
35
|
properties: {
|
|
@@ -24,6 +45,12 @@ module.exports = fp(async (fastify, options) => {
|
|
|
24
45
|
type: 'string',
|
|
25
46
|
description: '目标对象类型'
|
|
26
47
|
},
|
|
48
|
+
context: {
|
|
49
|
+
description: '执行上下文,任务执行时可读取;其中 secret 用于外部回调签名校验'
|
|
50
|
+
},
|
|
51
|
+
options: {
|
|
52
|
+
description: '任务扩展选项'
|
|
53
|
+
},
|
|
27
54
|
input: {
|
|
28
55
|
type: 'object',
|
|
29
56
|
description: '输入数据'
|
|
@@ -31,15 +58,15 @@ module.exports = fp(async (fastify, options) => {
|
|
|
31
58
|
runnerType: {
|
|
32
59
|
type: 'string',
|
|
33
60
|
enum: ['manual', 'system'],
|
|
34
|
-
description:
|
|
61
|
+
description: `执行者类型,${RUNNER_TYPE},默认 manual`
|
|
35
62
|
},
|
|
36
63
|
delay: {
|
|
37
64
|
type: 'number',
|
|
38
|
-
description: '
|
|
65
|
+
description: '延迟执行秒数,必须为非负数,默认 0 立即可执行'
|
|
39
66
|
},
|
|
40
67
|
scriptName: {
|
|
41
68
|
type: 'string',
|
|
42
|
-
description: '
|
|
69
|
+
description: '任务脚本名称(不含 .js),只能包含字母、数字、下划线或中划线;不传使用任务类型声明的脚本,默认 index'
|
|
43
70
|
},
|
|
44
71
|
priority: {
|
|
45
72
|
type: 'number',
|
|
@@ -59,7 +86,12 @@ module.exports = fp(async (fastify, options) => {
|
|
|
59
86
|
}
|
|
60
87
|
},
|
|
61
88
|
required: ['type', 'targetId', 'targetType']
|
|
62
|
-
}
|
|
89
|
+
},
|
|
90
|
+
response: success('创建成功', {
|
|
91
|
+
type: 'object',
|
|
92
|
+
additionalProperties: true,
|
|
93
|
+
properties: { id: any('新任务 ID') }
|
|
94
|
+
})
|
|
63
95
|
}
|
|
64
96
|
},
|
|
65
97
|
async request => {
|
|
@@ -73,71 +105,62 @@ module.exports = fp(async (fastify, options) => {
|
|
|
73
105
|
{
|
|
74
106
|
onRequest: options.getAuthenticate('read'),
|
|
75
107
|
schema: {
|
|
108
|
+
tags: [TAG],
|
|
76
109
|
summary: '获取任务列表',
|
|
110
|
+
description: '分页查询任务,默认按创建时间倒序;filter / sort 也支持 filter[key]=value 形式的扁平 query 参数',
|
|
77
111
|
query: {
|
|
78
112
|
type: 'object',
|
|
79
113
|
properties: {
|
|
80
114
|
perPage: {
|
|
81
115
|
type: 'number',
|
|
82
|
-
default: 20
|
|
116
|
+
default: 20,
|
|
117
|
+
description: '每页条数'
|
|
83
118
|
},
|
|
84
119
|
currentPage: {
|
|
85
120
|
type: 'number',
|
|
86
|
-
default: 1
|
|
121
|
+
default: 1,
|
|
122
|
+
description: '页码,从 1 开始'
|
|
87
123
|
},
|
|
88
124
|
filter: {
|
|
89
125
|
type: 'object',
|
|
126
|
+
description: '筛选条件',
|
|
90
127
|
properties: {
|
|
91
128
|
id: {
|
|
92
|
-
type: 'string'
|
|
129
|
+
type: 'string',
|
|
130
|
+
description: '任务ID'
|
|
93
131
|
},
|
|
94
132
|
targetId: {
|
|
95
|
-
type: 'string'
|
|
133
|
+
type: 'string',
|
|
134
|
+
description: '目标对象ID'
|
|
96
135
|
},
|
|
97
136
|
targetName: {
|
|
98
|
-
type: 'string'
|
|
137
|
+
type: 'string',
|
|
138
|
+
description: '目标对象名称,对应任务 input.name'
|
|
99
139
|
},
|
|
100
140
|
type: {
|
|
101
|
-
type: 'string'
|
|
141
|
+
type: 'string',
|
|
142
|
+
description: '任务类型'
|
|
102
143
|
},
|
|
103
144
|
status: {
|
|
104
|
-
type: 'string'
|
|
145
|
+
type: 'string',
|
|
146
|
+
description: TASK_STATUS
|
|
105
147
|
},
|
|
106
148
|
runnerType: {
|
|
107
|
-
type: 'string'
|
|
149
|
+
type: 'string',
|
|
150
|
+
description: RUNNER_TYPE
|
|
108
151
|
},
|
|
109
|
-
createdAt:
|
|
110
|
-
|
|
111
|
-
properties: {
|
|
112
|
-
startTime: {
|
|
113
|
-
type: 'string'
|
|
114
|
-
},
|
|
115
|
-
endTime: {
|
|
116
|
-
type: 'string'
|
|
117
|
-
}
|
|
118
|
-
},
|
|
119
|
-
description: 'createdAt区间查找'
|
|
120
|
-
},
|
|
121
|
-
completedAt: {
|
|
122
|
-
type: 'object',
|
|
123
|
-
properties: {
|
|
124
|
-
startTime: {
|
|
125
|
-
type: 'string'
|
|
126
|
-
},
|
|
127
|
-
endTime: {
|
|
128
|
-
type: 'string'
|
|
129
|
-
}
|
|
130
|
-
},
|
|
131
|
-
description: 'completedAt区间查找'
|
|
132
|
-
}
|
|
152
|
+
createdAt: timeRange('createdAt'),
|
|
153
|
+
completedAt: timeRange('completedAt')
|
|
133
154
|
}
|
|
134
155
|
},
|
|
135
156
|
sort: {
|
|
136
157
|
type: 'object',
|
|
137
|
-
description:
|
|
158
|
+
description:
|
|
159
|
+
"排序,键为字段名、值为 ASC 升序 / DESC 降序,如 { completedAt: 'DESC' };可排序字段:id、targetId、targetType、type、status、runnerType、priority、createdAt、updatedAt、startTime、startedAt、completedAt,其他字段报错"
|
|
138
160
|
}
|
|
139
161
|
}
|
|
140
|
-
}
|
|
162
|
+
},
|
|
163
|
+
response: success('任务分页结果', taskList)
|
|
141
164
|
}
|
|
142
165
|
},
|
|
143
166
|
async request => {
|
|
@@ -150,33 +173,43 @@ module.exports = fp(async (fastify, options) => {
|
|
|
150
173
|
{
|
|
151
174
|
onRequest: options.getAuthenticate('write'),
|
|
152
175
|
schema: {
|
|
176
|
+
tags: [TAG],
|
|
153
177
|
summary: '手动完成任务',
|
|
178
|
+
description: '人工把任务标记为成功或失败并记录完成人;成功时执行任务类型的完成回调,回调出错则转为失败;只有未结束的任务会被更新;只接受下列声明的字段,其它字段(如 context、userId)会被忽略',
|
|
154
179
|
body: {
|
|
155
180
|
type: 'object',
|
|
156
181
|
properties: {
|
|
157
182
|
id: {
|
|
158
|
-
type: 'string'
|
|
183
|
+
type: 'string',
|
|
184
|
+
description: '任务ID'
|
|
159
185
|
},
|
|
160
186
|
status: {
|
|
161
187
|
type: 'string',
|
|
162
|
-
enum: ['success', 'failed']
|
|
188
|
+
enum: ['success', 'failed'],
|
|
189
|
+
description: '完成结果:success 成功,failed 失败'
|
|
163
190
|
},
|
|
164
191
|
error: {
|
|
165
|
-
type: 'string'
|
|
192
|
+
type: 'string',
|
|
193
|
+
description: '失败原因,status 为 failed 时记录,不传记为「任务失败」'
|
|
166
194
|
},
|
|
167
195
|
msg: {
|
|
168
|
-
type: 'string'
|
|
196
|
+
type: 'string',
|
|
197
|
+
description: '任务消息,status 为 failed 时写入任务'
|
|
169
198
|
},
|
|
170
199
|
output: {
|
|
171
|
-
type: 'object'
|
|
200
|
+
type: 'object',
|
|
201
|
+
description: '任务输出数据'
|
|
172
202
|
}
|
|
173
203
|
},
|
|
174
204
|
required: ['id', 'status']
|
|
175
|
-
}
|
|
205
|
+
},
|
|
206
|
+
response: empty('操作成功,返回空对象')
|
|
176
207
|
}
|
|
177
208
|
},
|
|
178
209
|
async request => {
|
|
179
|
-
|
|
210
|
+
// 只透传 schema 声明的字段,避免客户端借失败分支覆盖 context.secret 等任意列
|
|
211
|
+
const { id, status, error, msg, output } = request.body;
|
|
212
|
+
await services.complete({ id, status, error, msg, output, userId: request.userInfo?.id });
|
|
180
213
|
return {};
|
|
181
214
|
}
|
|
182
215
|
);
|
|
@@ -186,7 +219,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
186
219
|
{
|
|
187
220
|
onRequest: options.getAuthenticate('write'),
|
|
188
221
|
schema: {
|
|
222
|
+
tags: [TAG],
|
|
189
223
|
summary: '取消任务',
|
|
224
|
+
description: '把 pending / running 状态的任务置为 canceled:传 id 取消单个任务;同时传 targetId、targetType、type 时批量取消该目标下该类型的任务(优先于 id);两种都没传报错',
|
|
190
225
|
body: {
|
|
191
226
|
type: 'object',
|
|
192
227
|
properties: {
|
|
@@ -207,7 +242,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
207
242
|
description: '任务类型(批量取消时使用)'
|
|
208
243
|
}
|
|
209
244
|
}
|
|
210
|
-
}
|
|
245
|
+
},
|
|
246
|
+
response: empty('操作成功,返回空对象')
|
|
211
247
|
}
|
|
212
248
|
},
|
|
213
249
|
async request => {
|
|
@@ -221,21 +257,26 @@ module.exports = fp(async (fastify, options) => {
|
|
|
221
257
|
{
|
|
222
258
|
onRequest: options.getAuthenticate('write'),
|
|
223
259
|
schema: {
|
|
260
|
+
tags: [TAG],
|
|
224
261
|
summary: '重试任务',
|
|
262
|
+
description: '把 failed / canceled 状态的任务重置为 pending 并清空完成信息、错误和重试计数,等待重新调度;其他状态报错,批量时遇到错误即中止',
|
|
225
263
|
body: {
|
|
226
264
|
type: 'object',
|
|
227
265
|
properties: {
|
|
228
266
|
id: {
|
|
229
|
-
type: 'string'
|
|
267
|
+
type: 'string',
|
|
268
|
+
description: '任务ID(单个重试)'
|
|
230
269
|
},
|
|
231
270
|
taskIds: {
|
|
232
271
|
type: 'array',
|
|
233
272
|
items: {
|
|
234
273
|
type: 'string'
|
|
235
|
-
}
|
|
274
|
+
},
|
|
275
|
+
description: '任务ID列表(批量重试),可与 id 同时传'
|
|
236
276
|
}
|
|
237
277
|
}
|
|
238
|
-
}
|
|
278
|
+
},
|
|
279
|
+
response: empty('操作成功,返回空对象')
|
|
239
280
|
}
|
|
240
281
|
},
|
|
241
282
|
async request => {
|
|
@@ -248,7 +289,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
248
289
|
`${options.prefix}/next`,
|
|
249
290
|
{
|
|
250
291
|
schema: {
|
|
292
|
+
tags: [CALLBACK_TAG],
|
|
251
293
|
summary: '处理任务next',
|
|
294
|
+
description: `外部服务回传 waiting 状态任务的执行结果:result 为 JSON 字符串,code 为 0 时任务成功(data 交给任务完成回调),否则任务失败;${SIGNATURE_HINT}。该接口不鉴权`,
|
|
252
295
|
body: {
|
|
253
296
|
type: 'object',
|
|
254
297
|
properties: {
|
|
@@ -258,14 +301,15 @@ module.exports = fp(async (fastify, options) => {
|
|
|
258
301
|
},
|
|
259
302
|
signature: {
|
|
260
303
|
type: 'string',
|
|
261
|
-
description: '
|
|
304
|
+
description: '签名:以任务 context.secret 为密钥,对 `${id}|${result}` 做 HMAC-SHA256 的十六进制摘要'
|
|
262
305
|
},
|
|
263
306
|
result: {
|
|
264
307
|
type: 'string',
|
|
265
|
-
description: '结果'
|
|
308
|
+
description: '结果 JSON 字符串,形如 {"code":0,"data":{}};解析失败任务置为失败'
|
|
266
309
|
}
|
|
267
310
|
}
|
|
268
|
-
}
|
|
311
|
+
},
|
|
312
|
+
response: { 200: { description: '处理完成,响应体为空' } }
|
|
269
313
|
}
|
|
270
314
|
},
|
|
271
315
|
async request => {
|
|
@@ -277,18 +321,23 @@ module.exports = fp(async (fastify, options) => {
|
|
|
277
321
|
`${options.prefix}/log`,
|
|
278
322
|
{
|
|
279
323
|
schema: {
|
|
324
|
+
tags: [CALLBACK_TAG],
|
|
280
325
|
summary: '记录任务日志',
|
|
326
|
+
description: `外部服务为任务追加一条日志,保存在任务 options.logs(新的在前,最多 100 条);${SIGNATURE_HINT}。该接口不鉴权`,
|
|
281
327
|
body: {
|
|
282
328
|
type: 'object',
|
|
283
329
|
properties: {
|
|
284
330
|
id: {
|
|
285
|
-
type: 'string'
|
|
331
|
+
type: 'string',
|
|
332
|
+
description: '任务ID,与 query.taskId 二选一,优先使用 id'
|
|
286
333
|
},
|
|
287
334
|
data: {
|
|
288
|
-
type: 'object'
|
|
335
|
+
type: 'object',
|
|
336
|
+
description: '日志数据'
|
|
289
337
|
},
|
|
290
338
|
message: {
|
|
291
|
-
type: 'string'
|
|
339
|
+
type: 'string',
|
|
340
|
+
description: '日志内容'
|
|
292
341
|
},
|
|
293
342
|
signature: {
|
|
294
343
|
type: 'string',
|
|
@@ -300,10 +349,12 @@ module.exports = fp(async (fastify, options) => {
|
|
|
300
349
|
type: 'object',
|
|
301
350
|
properties: {
|
|
302
351
|
taskId: {
|
|
303
|
-
type: 'string'
|
|
352
|
+
type: 'string',
|
|
353
|
+
description: '任务ID,body 未传 id 时使用'
|
|
304
354
|
}
|
|
305
355
|
}
|
|
306
|
-
}
|
|
356
|
+
},
|
|
357
|
+
response: success('更新后的任务记录', task)
|
|
307
358
|
}
|
|
308
359
|
},
|
|
309
360
|
async request => {
|
|
@@ -315,21 +366,27 @@ module.exports = fp(async (fastify, options) => {
|
|
|
315
366
|
`${options.prefix}/callback`,
|
|
316
367
|
{
|
|
317
368
|
schema: {
|
|
369
|
+
tags: [CALLBACK_TAG],
|
|
318
370
|
summary: '任务回调',
|
|
371
|
+
description: `外部服务回传任务最终结果:先把回调内容记入任务日志,code 为 0 时任务成功(data 作为输出),否则任务失败(message 作为错误);${SIGNATURE_HINT}。该接口不鉴权`,
|
|
319
372
|
body: {
|
|
320
373
|
type: 'object',
|
|
321
374
|
properties: {
|
|
322
375
|
id: {
|
|
323
|
-
type: 'string'
|
|
376
|
+
type: 'string',
|
|
377
|
+
description: '任务ID,与 query.taskId 二选一,优先使用 id'
|
|
324
378
|
},
|
|
325
379
|
code: {
|
|
326
|
-
type: 'number'
|
|
380
|
+
type: 'number',
|
|
381
|
+
description: '结果码,0 表示成功,其他表示失败'
|
|
327
382
|
},
|
|
328
383
|
data: {
|
|
329
|
-
type: 'object'
|
|
384
|
+
type: 'object',
|
|
385
|
+
description: '结果数据,作为任务输出'
|
|
330
386
|
},
|
|
331
387
|
message: {
|
|
332
|
-
type: 'string'
|
|
388
|
+
type: 'string',
|
|
389
|
+
description: '结果说明,失败时作为错误信息'
|
|
333
390
|
},
|
|
334
391
|
signature: {
|
|
335
392
|
type: 'string',
|
|
@@ -341,10 +398,12 @@ module.exports = fp(async (fastify, options) => {
|
|
|
341
398
|
type: 'object',
|
|
342
399
|
properties: {
|
|
343
400
|
taskId: {
|
|
344
|
-
type: 'string'
|
|
401
|
+
type: 'string',
|
|
402
|
+
description: '任务ID,body 未传 id 时使用'
|
|
345
403
|
}
|
|
346
404
|
}
|
|
347
|
-
}
|
|
405
|
+
},
|
|
406
|
+
response: { 200: { description: '处理完成,响应体为空' } }
|
|
348
407
|
}
|
|
349
408
|
},
|
|
350
409
|
async request => {
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
const fp = require('fastify-plugin');
|
|
2
|
+
const { success, statistics } = require('../schema/response');
|
|
3
|
+
|
|
4
|
+
const TAG = '任务-统计';
|
|
2
5
|
|
|
3
6
|
module.exports = fp(async (fastify, options) => {
|
|
4
7
|
const { services } = fastify[options.name];
|
|
@@ -8,7 +11,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
8
11
|
{
|
|
9
12
|
onRequest: options.getAuthenticate('statistics'),
|
|
10
13
|
schema: {
|
|
14
|
+
tags: [TAG],
|
|
11
15
|
summary: '获取任务统计概览',
|
|
16
|
+
description: '按时间范围汇总已结束任务的数量、状态/类型/执行方式分布、每日与按小时趋势及耗时;不支持的 range 报错,其他查询异常时返回空统计',
|
|
12
17
|
query: {
|
|
13
18
|
type: 'object',
|
|
14
19
|
properties: {
|
|
@@ -17,7 +22,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
17
22
|
type: { type: 'string', description: '按任务类型筛选' },
|
|
18
23
|
runnerType: { type: 'string', description: '按执行方式筛选 manual / system' }
|
|
19
24
|
}
|
|
20
|
-
}
|
|
25
|
+
},
|
|
26
|
+
response: success('任务统计数据', statistics)
|
|
21
27
|
}
|
|
22
28
|
},
|
|
23
29
|
async request => {
|
|
@@ -32,7 +38,9 @@ module.exports = fp(async (fastify, options) => {
|
|
|
32
38
|
{
|
|
33
39
|
onRequest: options.getAuthenticate('statistics'),
|
|
34
40
|
schema: {
|
|
41
|
+
tags: [TAG],
|
|
35
42
|
summary: 'SSE实时推送任务统计数据',
|
|
43
|
+
description: '以 text/event-stream 长连接按 interval 推送实时统计(当天各状态数量、执行中/等待中任务数等),客户端断开后停止',
|
|
36
44
|
query: {
|
|
37
45
|
type: 'object',
|
|
38
46
|
properties: {
|
|
@@ -42,7 +50,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
42
50
|
runnerType: { type: 'string', description: '按执行方式筛选 manual / system' },
|
|
43
51
|
interval: { type: 'integer', minimum: 1, default: 5, description: '推送间隔时间(秒),最小1秒,默认5秒' }
|
|
44
52
|
}
|
|
45
|
-
}
|
|
53
|
+
},
|
|
54
|
+
response: { 200: { description: 'text/event-stream 事件流,每条 data 为实时统计 JSON' } }
|
|
46
55
|
}
|
|
47
56
|
},
|
|
48
57
|
async (request, reply) => {
|
|
@@ -212,7 +212,17 @@ const createContext = (fastify, options) => {
|
|
|
212
212
|
const getTaskDeclaration = type => {
|
|
213
213
|
const declaration = resolveTaskDeclaration(type);
|
|
214
214
|
if (!declaration) {
|
|
215
|
-
|
|
215
|
+
const { taskName } = splitTaskName(type);
|
|
216
|
+
return registerTaskDeclaration({
|
|
217
|
+
namespace: mainNamespace,
|
|
218
|
+
taskName,
|
|
219
|
+
dirs: options.dirs,
|
|
220
|
+
scriptName: options.scriptName,
|
|
221
|
+
config: {},
|
|
222
|
+
override: false,
|
|
223
|
+
syncLegacyTask: false,
|
|
224
|
+
useGlobalDirs: true
|
|
225
|
+
}).declaration;
|
|
216
226
|
}
|
|
217
227
|
return declaration;
|
|
218
228
|
};
|
|
@@ -323,7 +333,7 @@ const createContext = (fastify, options) => {
|
|
|
323
333
|
return true;
|
|
324
334
|
};
|
|
325
335
|
|
|
326
|
-
const create = async ({ userId, input, type, targetId, targetType,
|
|
336
|
+
const create = async ({ userId, input, type, targetId, targetType, runnerType, delay = 0, scriptName, priority = 0, parentTaskId, maxRetries = 0, timeout = 60 * 60 * 1000, context, options: currentOptions }) => {
|
|
327
337
|
if (typeof delay !== 'number' || delay < 0) {
|
|
328
338
|
throw new Error('delay 必须为非负数');
|
|
329
339
|
}
|
|
@@ -344,7 +354,6 @@ const createContext = (fastify, options) => {
|
|
|
344
354
|
type: declaration.type,
|
|
345
355
|
targetId,
|
|
346
356
|
targetType,
|
|
347
|
-
targetName,
|
|
348
357
|
runnerType,
|
|
349
358
|
priority,
|
|
350
359
|
parentTaskId,
|
|
@@ -485,7 +494,6 @@ const createContext = (fastify, options) => {
|
|
|
485
494
|
type: nextDeclaration.type,
|
|
486
495
|
targetId: task.id,
|
|
487
496
|
targetType: 'task',
|
|
488
|
-
targetName: task.input?.name || task.targetName,
|
|
489
497
|
runnerType: task.runnerType,
|
|
490
498
|
input,
|
|
491
499
|
context: cloneJsonValue(task.context || {}),
|
package/libs/models/task.js
CHANGED
|
@@ -18,10 +18,6 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
|
|
|
18
18
|
comment: '任务目标对象类型',
|
|
19
19
|
allowNull: false
|
|
20
20
|
},
|
|
21
|
-
targetName: {
|
|
22
|
-
type: DataTypes.STRING,
|
|
23
|
-
comment: '任务目标对象名称'
|
|
24
|
-
},
|
|
25
21
|
runnerType: {
|
|
26
22
|
type: DataTypes.ENUM('manual', 'system'),
|
|
27
23
|
comment: '任务执行者类型: manual为手动执行, system为系统自动执行',
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// 响应 schema 只用于 OpenAPI 文档:字段可空、对象允许额外字段,避免序列化改变实际输出
|
|
2
|
+
const str = description => ({ type: 'string', nullable: true, description });
|
|
3
|
+
const num = description => ({ type: 'number', nullable: true, description });
|
|
4
|
+
// ID、日期、JSON 列可能是 number / string / Date / 任意结构,不声明类型,原样输出
|
|
5
|
+
const any = description => ({ description });
|
|
6
|
+
const obj = (description, properties = {}) => ({ type: 'object', nullable: true, additionalProperties: true, description, properties });
|
|
7
|
+
const list = (description, items) => ({ type: 'array', nullable: true, description, items });
|
|
8
|
+
|
|
9
|
+
const success = (description, schema) => ({ 200: Object.assign({}, schema || { type: 'object', additionalProperties: true }, { description }) });
|
|
10
|
+
const empty = description => success(description || '操作成功,返回空对象');
|
|
11
|
+
|
|
12
|
+
const TASK_STATUS = '任务状态:pending 待执行,running 执行中,waiting 等待外部回调/轮询,success 成功,failed 失败,canceled 已取消';
|
|
13
|
+
const RUNNER_TYPE = '执行方式:manual 手动执行,system 系统自动执行';
|
|
14
|
+
|
|
15
|
+
const task = obj('任务', {
|
|
16
|
+
id: any('任务 ID'),
|
|
17
|
+
type: str('任务类型'),
|
|
18
|
+
scriptName: str('任务脚本名称'),
|
|
19
|
+
targetId: any('任务目标对象 ID'),
|
|
20
|
+
targetType: str('任务目标对象类型'),
|
|
21
|
+
runnerType: str(RUNNER_TYPE),
|
|
22
|
+
priority: num('优先级,数值越大越优先'),
|
|
23
|
+
parentTaskId: any('父任务 ID'),
|
|
24
|
+
retryCount: num('已自动重试次数'),
|
|
25
|
+
maxRetries: num('最大自动重试次数,0 表示不自动重试'),
|
|
26
|
+
timeout: num('任务超时时间(毫秒),0 表示不超时'),
|
|
27
|
+
startTime: any('任务最早执行时间'),
|
|
28
|
+
startedAt: any('实际开始执行时间'),
|
|
29
|
+
completedAt: any('完成时间'),
|
|
30
|
+
userId: any('创建人用户 ID,系统创建为空'),
|
|
31
|
+
completedUserId: any('完成任务的用户 ID'),
|
|
32
|
+
input: any('输入数据'),
|
|
33
|
+
output: any('输出数据'),
|
|
34
|
+
error: any('错误信息'),
|
|
35
|
+
status: str(TASK_STATUS),
|
|
36
|
+
context: any('执行上下文,如回调签名密钥等'),
|
|
37
|
+
pollResults: any('轮询执行结果列表'),
|
|
38
|
+
pollCount: num('已轮询次数'),
|
|
39
|
+
progress: num('任务进度(0-100)'),
|
|
40
|
+
msg: str('任务消息或错误信息'),
|
|
41
|
+
options: any('扩展选项,logs 为最近 100 条任务日志(新的在前)'),
|
|
42
|
+
createdAt: any('创建时间'),
|
|
43
|
+
updatedAt: any('更新时间')
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const taskList = {
|
|
47
|
+
type: 'object',
|
|
48
|
+
additionalProperties: true,
|
|
49
|
+
properties: {
|
|
50
|
+
pageData: list('当前页任务列表,默认按创建时间倒序', task),
|
|
51
|
+
totalCount: num('符合条件的任务总数')
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const statistics = {
|
|
56
|
+
type: 'object',
|
|
57
|
+
additionalProperties: true,
|
|
58
|
+
properties: {
|
|
59
|
+
range: str('时间范围:7d / 1m / 3m / 1y'),
|
|
60
|
+
rangeLabel: str('时间范围名称,如「近7天」'),
|
|
61
|
+
totalTasks: num('范围内已结束(成功、失败、取消)的任务总数'),
|
|
62
|
+
byStatus: any('按状态统计的任务数,键为 success / failed / canceled'),
|
|
63
|
+
byType: any('按任务类型统计的任务数,键为任务类型'),
|
|
64
|
+
byRunnerType: any('按执行方式统计的任务数,键为 manual / system'),
|
|
65
|
+
recentTrend: any('每日趋势,每项为 { date, count }'),
|
|
66
|
+
recentTrendByStatus: any('每日按状态趋势,每项为 { date, status, count }'),
|
|
67
|
+
recentTrendByType: any('每日按类型趋势,每项为 { date, type, count }'),
|
|
68
|
+
durationTrend: any('每日耗时趋势,每项含 date、完成/成功/失败数及平均等待、执行、总耗时(毫秒)'),
|
|
69
|
+
hourlyTrend: any('按小时趋势,每项为 { date, hour, total, success, failed, canceled };查询失败或无数据时不返回'),
|
|
70
|
+
hourlyCompletionTrend: any('按小时、类型、执行方式的完成明细,每项含 date、hour、type、runnerType 及完成/成功/失败/取消数')
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
module.exports = { str, num, any, obj, list, success, empty, TASK_STATUS, RUNNER_TYPE, task, taskList, statistics };
|
|
@@ -25,10 +25,8 @@ const parseRange = (range = '7d', tz) => {
|
|
|
25
25
|
// 写入数据全使用服务器时间,查询用客户端时间
|
|
26
26
|
// 使用客户端时区计算"现在"和"起始时间",确保日期边界对齐客户端视角
|
|
27
27
|
const now = tz ? dayjs().tz(tz) : dayjs();
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
const startTime = startUnit
|
|
31
|
-
? now.subtract(config.value, startUnit).startOf(startUnit)
|
|
28
|
+
const startTime = config.unit === 'day'
|
|
29
|
+
? now.subtract(config.value, config.unit).startOf('day')
|
|
32
30
|
: now.subtract(config.value, config.unit);
|
|
33
31
|
return { startTime: startTime.toDate(), endTime: now.toDate(), label: config.label, range };
|
|
34
32
|
};
|
|
@@ -45,6 +43,13 @@ const getHour = (date, tz) => {
|
|
|
45
43
|
return d.hour();
|
|
46
44
|
};
|
|
47
45
|
|
|
46
|
+
const getZonedChannelHour = (periodTime, serverHour, tz) => {
|
|
47
|
+
if (!tz) return { date: formatDate(periodTime), hour: serverHour };
|
|
48
|
+
const localPeriodTime = dayjs(periodTime).hour(serverHour).minute(0).second(0).millisecond(0);
|
|
49
|
+
const zonedTime = localPeriodTime.tz(tz);
|
|
50
|
+
return { date: zonedTime.format('YYYY-MM-DD'), hour: zonedTime.hour() };
|
|
51
|
+
};
|
|
52
|
+
|
|
48
53
|
const safeNum = v => {
|
|
49
54
|
const n = Number(v);
|
|
50
55
|
return (typeof n === 'number' && !isNaN(n) ? n : 0);
|
|
@@ -64,9 +69,12 @@ const toAvgDuration = ({ count, sumWaiting, sumExecution, sumTotal }) => ({
|
|
|
64
69
|
|
|
65
70
|
const parseChannel = channel => {
|
|
66
71
|
const parts = channel.split(':');
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
72
|
+
const hour = Number(parts[2]);
|
|
73
|
+
return {
|
|
74
|
+
type: parts[0],
|
|
75
|
+
runnerType: parts.length >= 2 ? parts[1] : null,
|
|
76
|
+
completedHour: parts.length >= 3 && Number.isInteger(hour) && hour >= 0 && hour < 24 ? hour : null
|
|
77
|
+
};
|
|
70
78
|
};
|
|
71
79
|
|
|
72
80
|
const buildChannels = async (statisticsServices, type, runnerType) => {
|
|
@@ -83,6 +91,20 @@ const buildChannels = async (statisticsServices, type, runnerType) => {
|
|
|
83
91
|
return channels;
|
|
84
92
|
};
|
|
85
93
|
|
|
94
|
+
const buildHourlyChannels = (channels, runnerType) => {
|
|
95
|
+
const types = [...new Set(channels.map(ch => ch.split(':')[0]).filter(Boolean))];
|
|
96
|
+
const runnerTypes = runnerType ? [runnerType] : RUNNER_TYPES;
|
|
97
|
+
const hourlyChannels = [];
|
|
98
|
+
for (const type of types) {
|
|
99
|
+
for (const rt of runnerTypes) {
|
|
100
|
+
for (let hour = 0; hour < 24; hour += 1) {
|
|
101
|
+
hourlyChannels.push(`${type}:${rt}:${hour}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return hourlyChannels;
|
|
106
|
+
};
|
|
107
|
+
|
|
86
108
|
// 确保时长累加器存在于 map 中
|
|
87
109
|
const ensureDurationAcc = (map, key) => {
|
|
88
110
|
if (!map[key]) map[key] = { count: 0, sumWaiting: 0, sumExecution: 0, sumTotal: 0 };
|
|
@@ -104,9 +126,48 @@ const createDailyMapEntry = () => ({ total: 0, byStatus: { success: 0, failed: 0
|
|
|
104
126
|
const createDailyDurationEntry = () => ({
|
|
105
127
|
completedCount: 0, successCount: 0, failedCount: 0, canceledCount: 0,
|
|
106
128
|
sumWaiting: 0, sumExecution: 0, sumTotal: 0, countWithTiming: 0,
|
|
107
|
-
byType: {}, byRunnerType: {}
|
|
129
|
+
byType: {}, byRunnerType: {}, byTypeByRunnerType: {}
|
|
108
130
|
});
|
|
109
131
|
|
|
132
|
+
const createHourlyAccumulator = () => ({
|
|
133
|
+
hourlyMap: {},
|
|
134
|
+
hourlyStatusMap: {},
|
|
135
|
+
hourlyTypeMap: {},
|
|
136
|
+
hourlyDetailMap: {}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const mergeHourlyItem = (result, { date, hour, typeName, runnerTypeName, count, sum, includeSummary = true }) => {
|
|
140
|
+
if (includeSummary) {
|
|
141
|
+
if (!result.hourlyMap[date]) result.hourlyMap[date] = {};
|
|
142
|
+
result.hourlyMap[date][hour] = (result.hourlyMap[date][hour] || 0) + count;
|
|
143
|
+
|
|
144
|
+
if (!result.hourlyStatusMap[date]) result.hourlyStatusMap[date] = {};
|
|
145
|
+
if (!result.hourlyStatusMap[date][hour]) result.hourlyStatusMap[date][hour] = {};
|
|
146
|
+
for (const status of ['success', 'failed', 'canceled']) {
|
|
147
|
+
const sc = safeNum(sum[status]);
|
|
148
|
+
if (sc > 0) result.hourlyStatusMap[date][hour][status] = (result.hourlyStatusMap[date][hour][status] || 0) + sc;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (!result.hourlyTypeMap[date]) result.hourlyTypeMap[date] = {};
|
|
152
|
+
if (!result.hourlyTypeMap[date][hour]) result.hourlyTypeMap[date][hour] = {};
|
|
153
|
+
if (count > 0) result.hourlyTypeMap[date][hour][typeName] = (result.hourlyTypeMap[date][hour][typeName] || 0) + count;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (runnerTypeName) {
|
|
157
|
+
if (!result.hourlyDetailMap[date]) result.hourlyDetailMap[date] = {};
|
|
158
|
+
if (!result.hourlyDetailMap[date][hour]) result.hourlyDetailMap[date][hour] = {};
|
|
159
|
+
if (!result.hourlyDetailMap[date][hour][typeName]) result.hourlyDetailMap[date][hour][typeName] = {};
|
|
160
|
+
if (!result.hourlyDetailMap[date][hour][typeName][runnerTypeName]) {
|
|
161
|
+
result.hourlyDetailMap[date][hour][typeName][runnerTypeName] = { total: 0, success: 0, failed: 0, canceled: 0 };
|
|
162
|
+
}
|
|
163
|
+
const detail = result.hourlyDetailMap[date][hour][typeName][runnerTypeName];
|
|
164
|
+
detail.total += count;
|
|
165
|
+
detail.success += safeNum(sum.success);
|
|
166
|
+
detail.failed += safeNum(sum.failed);
|
|
167
|
+
detail.canceled += safeNum(sum.canceled);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
|
|
110
171
|
// 查询 statistics 并解析结果
|
|
111
172
|
// 写入数据全使用服务器时间(DB 中存储的是服务器时间),查询用客户端时间转换展示
|
|
112
173
|
const queryAndParse = async (statisticsServices, { channels, startTime, endTime, timezone: tz, runnerType: runnerTypeFilter }) => {
|
|
@@ -194,19 +255,7 @@ const queryAndParse = async (statisticsServices, { channels, startTime, endTime,
|
|
|
194
255
|
|
|
195
256
|
// 小时级趋势(仅 period='h')
|
|
196
257
|
if (isHourly) {
|
|
197
|
-
|
|
198
|
-
result.hourlyMap[date][hour] = (result.hourlyMap[date][hour] || 0) + count;
|
|
199
|
-
|
|
200
|
-
if (!result.hourlyStatusMap[date]) result.hourlyStatusMap[date] = {};
|
|
201
|
-
if (!result.hourlyStatusMap[date][hour]) result.hourlyStatusMap[date][hour] = {};
|
|
202
|
-
for (const status of ['success', 'failed', 'canceled']) {
|
|
203
|
-
const sc = safeNum(sum[status]);
|
|
204
|
-
if (sc > 0) result.hourlyStatusMap[date][hour][status] = (result.hourlyStatusMap[date][hour][status] || 0) + sc;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
if (!result.hourlyTypeMap[date]) result.hourlyTypeMap[date] = {};
|
|
208
|
-
if (!result.hourlyTypeMap[date][hour]) result.hourlyTypeMap[date][hour] = {};
|
|
209
|
-
if (count > 0) result.hourlyTypeMap[date][hour][typeName] = (result.hourlyTypeMap[date][hour][typeName] || 0) + count;
|
|
258
|
+
mergeHourlyItem(result, { date, hour, typeName, runnerTypeName: null, count, sum });
|
|
210
259
|
}
|
|
211
260
|
}
|
|
212
261
|
|
|
@@ -229,22 +278,20 @@ const queryAndParse = async (statisticsServices, { channels, startTime, endTime,
|
|
|
229
278
|
// 按日 byRunnerType 时长
|
|
230
279
|
if (dailyDurationMap[date]) {
|
|
231
280
|
accumDuration(ensureDurationAcc(dailyDurationMap[date].byRunnerType, runnerTypeName), count, sum);
|
|
281
|
+
if (!dailyDurationMap[date].byTypeByRunnerType[runnerTypeName]) {
|
|
282
|
+
dailyDurationMap[date].byTypeByRunnerType[runnerTypeName] = {};
|
|
283
|
+
}
|
|
284
|
+
accumDuration(
|
|
285
|
+
ensureDurationAcc(dailyDurationMap[date].byTypeByRunnerType[runnerTypeName], typeName),
|
|
286
|
+
count,
|
|
287
|
+
sum
|
|
288
|
+
);
|
|
232
289
|
}
|
|
233
290
|
}
|
|
234
291
|
|
|
235
292
|
// hourlyDetailMap(仅 period='h')
|
|
236
293
|
if (isHourly) {
|
|
237
|
-
|
|
238
|
-
if (!result.hourlyDetailMap[date][hour]) result.hourlyDetailMap[date][hour] = {};
|
|
239
|
-
if (!result.hourlyDetailMap[date][hour][typeName]) result.hourlyDetailMap[date][hour][typeName] = {};
|
|
240
|
-
if (!result.hourlyDetailMap[date][hour][typeName][runnerTypeName]) {
|
|
241
|
-
result.hourlyDetailMap[date][hour][typeName][runnerTypeName] = { total: 0, success: 0, failed: 0, canceled: 0 };
|
|
242
|
-
}
|
|
243
|
-
const detail = result.hourlyDetailMap[date][hour][typeName][runnerTypeName];
|
|
244
|
-
detail.total += count;
|
|
245
|
-
detail.success += safeNum(sum.success);
|
|
246
|
-
detail.failed += safeNum(sum.failed);
|
|
247
|
-
detail.canceled += safeNum(sum.canceled);
|
|
294
|
+
mergeHourlyItem(result, { date, hour, typeName, runnerTypeName, count, sum, includeSummary: false });
|
|
248
295
|
}
|
|
249
296
|
}
|
|
250
297
|
}
|
|
@@ -262,12 +309,51 @@ const queryAndParse = async (statisticsServices, { channels, startTime, endTime,
|
|
|
262
309
|
avgExecutionTime: computeAvg(dd.sumExecution, dd.countWithTiming),
|
|
263
310
|
avgTotalTime: computeAvg(dd.sumTotal, dd.countWithTiming),
|
|
264
311
|
byType: Object.fromEntries(Object.entries(dd.byType).map(([n, td]) => [n, toAvgDuration(td)])),
|
|
265
|
-
byRunnerType: Object.fromEntries(Object.entries(dd.byRunnerType).map(([n, rt]) => [n, toAvgDuration(rt)]))
|
|
312
|
+
byRunnerType: Object.fromEntries(Object.entries(dd.byRunnerType).map(([n, rt]) => [n, toAvgDuration(rt)])),
|
|
313
|
+
byTypeByRunnerType: Object.fromEntries(
|
|
314
|
+
Object.entries(dd.byTypeByRunnerType).map(([rtName, types]) => [
|
|
315
|
+
rtName,
|
|
316
|
+
Object.fromEntries(Object.entries(types).map(([typeName, td]) => [typeName, toAvgDuration(td)]))
|
|
317
|
+
])
|
|
318
|
+
)
|
|
266
319
|
}));
|
|
267
320
|
|
|
268
321
|
return result;
|
|
269
322
|
};
|
|
270
323
|
|
|
324
|
+
const queryHourlyChildChannels = async (statisticsServices, { channels, startTime, endTime, timezone: tz, runnerType: runnerTypeFilter }) => {
|
|
325
|
+
const hourlyChannels = buildHourlyChannels(channels, runnerTypeFilter);
|
|
326
|
+
if (hourlyChannels.length === 0) return null;
|
|
327
|
+
|
|
328
|
+
const statResult = await statisticsServices.query({
|
|
329
|
+
channels: hourlyChannels, startTime, endTime,
|
|
330
|
+
attributeNames: STAT_ATTRS,
|
|
331
|
+
aggregates: ['sum'],
|
|
332
|
+
timezone: tz || undefined
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
const result = createHourlyAccumulator();
|
|
336
|
+
for (const item of statResult.list || []) {
|
|
337
|
+
const { type: typeName, runnerType: runnerTypeName, completedHour } = parseChannel(item.channel);
|
|
338
|
+
if (completedHour == null) continue;
|
|
339
|
+
if (runnerTypeFilter && runnerTypeName !== runnerTypeFilter) continue;
|
|
340
|
+
|
|
341
|
+
const sum = getSumData(item);
|
|
342
|
+
const count = safeNum(sum.total);
|
|
343
|
+
const { date, hour } = getZonedChannelHour(item.time, completedHour, tz);
|
|
344
|
+
mergeHourlyItem(result, {
|
|
345
|
+
date,
|
|
346
|
+
hour,
|
|
347
|
+
typeName,
|
|
348
|
+
runnerTypeName,
|
|
349
|
+
count,
|
|
350
|
+
sum
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return result;
|
|
355
|
+
};
|
|
356
|
+
|
|
271
357
|
// 构建 todayDuration 结果
|
|
272
358
|
const buildDurationResult = (d) => ({
|
|
273
359
|
completedCount: d.completedCount,
|
|
@@ -379,9 +465,10 @@ module.exports = fp(async (fastify, options) => {
|
|
|
379
465
|
const channels = await buildChannels(statisticsServices, type, runnerType);
|
|
380
466
|
const parsed = await queryAndParse(statisticsServices, { channels, startTime, endTime, timezone, runnerType });
|
|
381
467
|
if (!parsed) return emptyResult;
|
|
468
|
+
const hourlyParsed = await queryHourlyChildChannels(statisticsServices, { channels, startTime, endTime, timezone, runnerType });
|
|
382
469
|
|
|
383
470
|
const { recentTrend, recentTrendByStatus, recentTrendByType } = buildDailyTrendArrays(parsed);
|
|
384
|
-
const { hourlyTrend, hourlyCompletionTrend } = buildHourlyTrendArrays(
|
|
471
|
+
const { hourlyTrend, hourlyCompletionTrend } = buildHourlyTrendArrays(hourlyParsed || createHourlyAccumulator());
|
|
385
472
|
|
|
386
473
|
return {
|
|
387
474
|
range: rangeKey, rangeLabel: label,
|
package/libs/services/task.js
CHANGED
|
@@ -4,7 +4,9 @@ const getTaskServiceContext = require('../helpers/task-service-context');
|
|
|
4
4
|
module.exports = fp(async (fastify, options) => {
|
|
5
5
|
const context = getTaskServiceContext(fastify, options);
|
|
6
6
|
const { models, Op } = context;
|
|
7
|
-
const
|
|
7
|
+
const Sequelize = fastify.sequelize.Sequelize;
|
|
8
|
+
const SORTABLE_FIELDS = new Set(['id', 'targetId', 'targetType', 'type', 'status', 'runnerType', 'priority', 'createdAt', 'updatedAt', 'startTime', 'startedAt', 'completedAt']);
|
|
9
|
+
const INTEGER_PRIORITY_MAX = 2147483647;
|
|
8
10
|
|
|
9
11
|
const cancel = async ({ id, targetId, targetType, type }) => {
|
|
10
12
|
if (!id && !(targetId && targetType && type)) {
|
|
@@ -73,7 +75,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
73
75
|
await context.updateTaskByStatus({
|
|
74
76
|
task,
|
|
75
77
|
allowedStatuses: ['pending'],
|
|
76
|
-
updateData: { priority:
|
|
78
|
+
updateData: { priority: INTEGER_PRIORITY_MAX }
|
|
77
79
|
});
|
|
78
80
|
const claimedTask = await fastify[options.name].services.claimTask(task);
|
|
79
81
|
if (claimedTask) {
|
|
@@ -142,7 +144,76 @@ module.exports = fp(async (fastify, options) => {
|
|
|
142
144
|
}
|
|
143
145
|
};
|
|
144
146
|
|
|
145
|
-
const
|
|
147
|
+
const normalizeListQuery = (query = {}) => {
|
|
148
|
+
const normalized = Object.assign({}, query);
|
|
149
|
+
|
|
150
|
+
Object.entries(query || {}).forEach(([rawKey, value]) => {
|
|
151
|
+
const match = rawKey.match(/^(filter|sort)\[([^\]]+)\](?:\[([^\]]+)\])?$/);
|
|
152
|
+
if (!match) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const [, root, key, childKey] = match;
|
|
157
|
+
if (!normalized[root] || typeof normalized[root] !== 'object' || Array.isArray(normalized[root])) {
|
|
158
|
+
normalized[root] = {};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (childKey) {
|
|
162
|
+
if (!normalized[root][key] || typeof normalized[root][key] !== 'object' || Array.isArray(normalized[root][key])) {
|
|
163
|
+
normalized[root][key] = {};
|
|
164
|
+
}
|
|
165
|
+
normalized[root][key][childKey] = value;
|
|
166
|
+
} else {
|
|
167
|
+
normalized[root][key] = value;
|
|
168
|
+
}
|
|
169
|
+
delete normalized[rawKey];
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
return normalized;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const quoteIdentifier = identifier => `"${String(identifier).replaceAll('"', '""')}"`;
|
|
176
|
+
|
|
177
|
+
const getJsonTextExpression = fieldPath => {
|
|
178
|
+
if (typeof Sequelize.literal !== 'function') {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const [field, key] = String(fieldPath).split('.');
|
|
183
|
+
const column = quoteIdentifier(models.task.rawAttributes?.[field]?.field || field);
|
|
184
|
+
const dialect = models.task.sequelize?.getDialect?.();
|
|
185
|
+
|
|
186
|
+
if (dialect === 'postgres') {
|
|
187
|
+
return Sequelize.literal(`${column}->>'${key}'`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (dialect === 'sqlite') {
|
|
191
|
+
return Sequelize.literal(`json_extract(${column}, '$.${key}')`);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return typeof Sequelize.json === 'function' ? Sequelize.json(fieldPath) : null;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const appendJsonFieldLikeFilter = (whereQuery, fieldPath, value) => {
|
|
198
|
+
const keyword = String(value).toLowerCase();
|
|
199
|
+
const condition = {
|
|
200
|
+
[Op.like]: `%${keyword}%`
|
|
201
|
+
};
|
|
202
|
+
const fallbackCondition = {
|
|
203
|
+
[Op.like]: `%${value}%`
|
|
204
|
+
};
|
|
205
|
+
const jsonTextExpression = getJsonTextExpression(fieldPath);
|
|
206
|
+
|
|
207
|
+
if (typeof Sequelize.where === 'function' && typeof Sequelize.fn === 'function' && jsonTextExpression && Op.and) {
|
|
208
|
+
whereQuery[Op.and] = [...(whereQuery[Op.and] || []), Sequelize.where(Sequelize.fn('lower', jsonTextExpression), condition)];
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
whereQuery[fieldPath] = fallbackCondition;
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const list = async query => {
|
|
216
|
+
const { filter, perPage = 20, currentPage = 1, sort } = normalizeListQuery(query);
|
|
146
217
|
const whereQuery = {};
|
|
147
218
|
|
|
148
219
|
['id', 'targetId', 'type', 'status', 'runnerType'].forEach(key => {
|
|
@@ -152,9 +223,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
152
223
|
});
|
|
153
224
|
|
|
154
225
|
if (filter && filter.targetName) {
|
|
155
|
-
whereQuery
|
|
156
|
-
[Op.like]: `%${filter.targetName}%`
|
|
157
|
-
};
|
|
226
|
+
appendJsonFieldLikeFilter(whereQuery, 'input.name', filter.targetName);
|
|
158
227
|
}
|
|
159
228
|
|
|
160
229
|
if (filter && filter.createdAt) {
|