@kne/fastify-task 3.0.2 → 3.0.4
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 +518 -424
- package/libs/controllers/main.js +11 -4
- package/libs/helpers/task-service-context.js +29 -2
- package/libs/services/callback.js +36 -5
- package/libs/services/task.js +17 -12
- package/package.json +1 -1
package/libs/controllers/main.js
CHANGED
|
@@ -368,7 +368,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
368
368
|
schema: {
|
|
369
369
|
tags: [CALLBACK_TAG],
|
|
370
370
|
summary: '任务回调',
|
|
371
|
-
description:
|
|
371
|
+
description: `外部服务回传任务结果:先把回调内容记入任务日志,code 为 0 时任务成功(data 作为输出),否则任务失败(message 作为错误);code 为 0 且传了小于 100 的 progress 时只上报进度(更新任务 progress 并记日志,任务保持原状态);${SIGNATURE_HINT}。该接口不鉴权`,
|
|
372
372
|
body: {
|
|
373
373
|
type: 'object',
|
|
374
374
|
properties: {
|
|
@@ -378,7 +378,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
378
378
|
},
|
|
379
379
|
code: {
|
|
380
380
|
type: 'number',
|
|
381
|
-
description: '
|
|
381
|
+
description: '结果码(必填),0 表示成功,其他表示失败'
|
|
382
382
|
},
|
|
383
383
|
data: {
|
|
384
384
|
type: 'object',
|
|
@@ -386,13 +386,20 @@ module.exports = fp(async (fastify, options) => {
|
|
|
386
386
|
},
|
|
387
387
|
message: {
|
|
388
388
|
type: 'string',
|
|
389
|
-
description: '
|
|
389
|
+
description: '结果说明,失败时作为错误信息;进度上报时作为日志说明'
|
|
390
|
+
},
|
|
391
|
+
progress: {
|
|
392
|
+
type: 'number',
|
|
393
|
+
minimum: 0,
|
|
394
|
+
maximum: 100,
|
|
395
|
+
description: '任务进度 0-100。code 为 0 且小于 100 时仅上报进度,任务不结束;不传或为 100 时按最终结果处理'
|
|
390
396
|
},
|
|
391
397
|
signature: {
|
|
392
398
|
type: 'string',
|
|
393
399
|
description: 'HMAC-SHA256签名'
|
|
394
400
|
}
|
|
395
|
-
}
|
|
401
|
+
},
|
|
402
|
+
required: ['code']
|
|
396
403
|
},
|
|
397
404
|
query: {
|
|
398
405
|
type: 'object',
|
|
@@ -110,14 +110,17 @@ const createContext = (fastify, options) => {
|
|
|
110
110
|
return { handler: config };
|
|
111
111
|
}
|
|
112
112
|
if (config && typeof config === 'object' && !Array.isArray(config)) {
|
|
113
|
-
const { handler, errorHandler, next } = config;
|
|
113
|
+
const { handler, errorHandler, cancelHandler, next } = config;
|
|
114
114
|
if (handler != null && typeof handler !== 'function') {
|
|
115
115
|
throw new Error(`任务 ${taskName} 的 handler 必须是一个函数`);
|
|
116
116
|
}
|
|
117
117
|
if (errorHandler != null && typeof errorHandler !== 'function') {
|
|
118
118
|
throw new Error(`任务 ${taskName} 的 errorHandler 必须是一个函数`);
|
|
119
119
|
}
|
|
120
|
-
|
|
120
|
+
if (cancelHandler != null && typeof cancelHandler !== 'function') {
|
|
121
|
+
throw new Error(`任务 ${taskName} 的 cancelHandler 必须是一个函数`);
|
|
122
|
+
}
|
|
123
|
+
return { handler, errorHandler, cancelHandler, next };
|
|
121
124
|
}
|
|
122
125
|
throw new Error(`任务 ${taskName} 的 handler 必须是一个函数`);
|
|
123
126
|
};
|
|
@@ -137,6 +140,7 @@ const createContext = (fastify, options) => {
|
|
|
137
140
|
scriptName: scriptName || (namespace === mainNamespace ? options.scriptName : 'index'),
|
|
138
141
|
handler: normalizedConfig.handler,
|
|
139
142
|
errorHandler: normalizedConfig.errorHandler,
|
|
143
|
+
cancelHandler: normalizedConfig.cancelHandler,
|
|
140
144
|
next: normalizedConfig.next
|
|
141
145
|
};
|
|
142
146
|
options.taskRegistry[registryKey] = declaration;
|
|
@@ -242,6 +246,12 @@ const createContext = (fastify, options) => {
|
|
|
242
246
|
return declaration.errorHandler;
|
|
243
247
|
};
|
|
244
248
|
|
|
249
|
+
const getTaskCancelHandler = declaration => {
|
|
250
|
+
const legacyConfig = options.task[declaration.type] || (declaration.namespace === mainNamespace ? options.task[declaration.taskName] : null);
|
|
251
|
+
if (legacyConfig && typeof legacyConfig === 'object' && typeof legacyConfig.cancelHandler === 'function') return legacyConfig.cancelHandler;
|
|
252
|
+
return declaration.cancelHandler;
|
|
253
|
+
};
|
|
254
|
+
|
|
245
255
|
const getTaskNext = declaration => {
|
|
246
256
|
const legacyConfig = options.task[declaration.type] || (declaration.namespace === mainNamespace ? options.task[declaration.taskName] : null);
|
|
247
257
|
if (legacyConfig && typeof legacyConfig === 'object' && Object.prototype.hasOwnProperty.call(legacyConfig, 'next')) return legacyConfig.next;
|
|
@@ -294,6 +304,22 @@ const createContext = (fastify, options) => {
|
|
|
294
304
|
return true;
|
|
295
305
|
};
|
|
296
306
|
|
|
307
|
+
// 任务被取消后的通知:任务级 cancelHandler 优先,未配置时调用全局 options.cancelHandler;
|
|
308
|
+
// 取消已经生效,处理器抛错只记录日志,不影响取消结果
|
|
309
|
+
const handleTaskCancel = async ({ task }) => {
|
|
310
|
+
const declaration = resolveTaskDeclaration(task.type);
|
|
311
|
+
const taskCancelHandler = declaration && getTaskCancelHandler(declaration);
|
|
312
|
+
const cancelHandler = typeof taskCancelHandler === 'function' ? taskCancelHandler : options.cancelHandler;
|
|
313
|
+
if (typeof cancelHandler !== 'function') {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
await cancelHandler({ task, context: task.context });
|
|
318
|
+
} catch (e) {
|
|
319
|
+
fastify.log.error(e);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
297
323
|
const handleTaskError = async ({ task, error }) => {
|
|
298
324
|
const declaration = resolveTaskDeclaration(task.type);
|
|
299
325
|
let currentError = error;
|
|
@@ -551,6 +577,7 @@ const createContext = (fastify, options) => {
|
|
|
551
577
|
resolveTaskDeclaration,
|
|
552
578
|
detail,
|
|
553
579
|
failTask,
|
|
580
|
+
handleTaskCancel,
|
|
554
581
|
create,
|
|
555
582
|
executor,
|
|
556
583
|
finalizeSuccess
|
|
@@ -66,11 +66,41 @@ module.exports = fp(async (fastify, options) => {
|
|
|
66
66
|
return log({ id: targetId, data, message });
|
|
67
67
|
};
|
|
68
68
|
|
|
69
|
-
const
|
|
69
|
+
const ACTIVE_STATUSES = ['pending', 'running', 'waiting'];
|
|
70
|
+
|
|
71
|
+
const normalizeProgress = progress => {
|
|
72
|
+
if (progress == null) return null;
|
|
73
|
+
if (typeof progress !== 'number' || !Number.isFinite(progress) || progress < 0 || progress > 100) {
|
|
74
|
+
throw new Error('progress 必须是 0-100 之间的数字');
|
|
75
|
+
}
|
|
76
|
+
return progress;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// 进度上报:只更新进度并记日志,任务保持原状态,不触发 handler / next / errorHandler
|
|
80
|
+
const reportProgress = async ({ id, code, data, message, progress }) => {
|
|
81
|
+
const task = await context.detail({ id });
|
|
82
|
+
const updated = await context.updateTaskByStatus({
|
|
83
|
+
task,
|
|
84
|
+
allowedStatuses: ACTIVE_STATUSES,
|
|
85
|
+
updateData: { progress: Math.round(progress) }
|
|
86
|
+
});
|
|
87
|
+
if (!updated) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
await log({ id, message: message || '进度回调', data: { code, data, message, progress } });
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const callback = async ({ id, code, data, message, progress }) => {
|
|
70
94
|
await context.detail({ id });
|
|
71
95
|
|
|
96
|
+
const currentProgress = normalizeProgress(progress);
|
|
97
|
+
// code 为 0 且 progress 小于 100 视为进度上报;不带 progress 或 progress 为 100 时与原来一致,按最终结果处理
|
|
98
|
+
if (code === 0 && currentProgress != null && currentProgress < 100) {
|
|
99
|
+
return reportProgress({ id, code, data, message, progress: currentProgress });
|
|
100
|
+
}
|
|
101
|
+
|
|
72
102
|
const result = { code, data, message };
|
|
73
|
-
await log({ id, message: '回调结果', data:
|
|
103
|
+
await log({ id, message: '回调结果', data: result });
|
|
74
104
|
const input = Object.assign(
|
|
75
105
|
{},
|
|
76
106
|
{ id },
|
|
@@ -88,15 +118,16 @@ module.exports = fp(async (fastify, options) => {
|
|
|
88
118
|
await fastify[options.name].services.complete(input);
|
|
89
119
|
};
|
|
90
120
|
|
|
91
|
-
const callbackWithSignature = async ({ id, taskId, code, data, message, signature }) => {
|
|
121
|
+
const callbackWithSignature = async ({ id, taskId, code, data, message, progress, signature }) => {
|
|
92
122
|
const targetId = id || taskId;
|
|
93
123
|
const task = await context.detail({ id: targetId });
|
|
94
124
|
|
|
95
|
-
|
|
125
|
+
// progress 为 undefined 时 JSON 序列化会忽略该字段,签名内容与不带进度的旧回调完全一致
|
|
126
|
+
if (task.context?.secret && !context.verifySignature({ secret: task.context.secret, id: targetId, data: { code, data, message, progress }, signature })) {
|
|
96
127
|
throw new Error('签名验证失败');
|
|
97
128
|
}
|
|
98
129
|
|
|
99
|
-
return callback({ id: targetId, code, data, message });
|
|
130
|
+
return callback({ id: targetId, code, data, message, progress });
|
|
100
131
|
};
|
|
101
132
|
|
|
102
133
|
Object.assign(fastify[options.name].services, {
|
package/libs/services/task.js
CHANGED
|
@@ -21,19 +21,23 @@ module.exports = fp(async (fastify, options) => {
|
|
|
21
21
|
[Op.in]: ['pending', 'running']
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
-
const tasksToCancel = await models.task.findAll({ where: bulkWhere
|
|
25
|
-
|
|
26
|
-
const
|
|
27
|
-
{
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
24
|
+
const tasksToCancel = await models.task.findAll({ where: bulkWhere });
|
|
25
|
+
let affectedCount = 0;
|
|
26
|
+
for (const task of tasksToCancel) {
|
|
27
|
+
const transitioned = await context.updateTaskByStatus({
|
|
28
|
+
task,
|
|
29
|
+
allowedStatuses: ['pending', 'running'],
|
|
30
|
+
updateData: {
|
|
31
|
+
status: 'canceled',
|
|
32
|
+
completedAt: new Date()
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
if (!transitioned) {
|
|
36
|
+
continue;
|
|
33
37
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
context.
|
|
38
|
+
affectedCount++;
|
|
39
|
+
context.collectTaskStatistics(task);
|
|
40
|
+
await context.handleTaskCancel({ task });
|
|
37
41
|
}
|
|
38
42
|
return affectedCount;
|
|
39
43
|
}
|
|
@@ -51,6 +55,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
51
55
|
return;
|
|
52
56
|
}
|
|
53
57
|
context.collectTaskStatistics(task);
|
|
58
|
+
await context.handleTaskCancel({ task });
|
|
54
59
|
}
|
|
55
60
|
};
|
|
56
61
|
|