@kne/fastify-task 3.0.0-alpha.0 → 3.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -13,12 +13,16 @@ module.exports = fp(
13
13
  dir: path.resolve(process.cwd(), 'libs', 'tasks'),
14
14
  /** 任务目录列表,运行时可通过 addDir 动态添加 */
15
15
  dirs: null,
16
- cronTime: '*/10 * * * *',
16
+ cronTime: '*/1 * * * *',
17
17
  scriptName: 'index',
18
18
  maxPollTimes: 20,
19
19
  pollInterval: 10000,
20
- /** 任务执行超时时间(毫秒),0 表示不超时,默认 30 分钟 */
20
+ /** 任务执行超时时间(毫秒),0 表示不超时,默认 1800000ms */
21
21
  taskTimeout: 30 * 60 * 1000,
22
+ /** 启动时仅恢复超出该时间窗口的 running 任务,避免多实例重启误重置正在执行的任务 */
23
+ recoverRunningTaskAfter: null,
24
+ /** 是否在启动时恢复陈旧 running 任务 */
25
+ recoverRunningTasksOnStart: true,
22
26
  /** 重试基础延迟(毫秒),实际延迟 = retryBaseDelay * 2^(retryCount-1) */
23
27
  retryBaseDelay: 5000,
24
28
  getUserModel: () => {
@@ -32,6 +36,10 @@ module.exports = fp(
32
36
  options
33
37
  );
34
38
 
39
+ if (options.recoverRunningTaskAfter == null) {
40
+ options.recoverRunningTaskAfter = options.taskTimeout > 0 ? options.taskTimeout : 30 * 60 * 1000;
41
+ }
42
+
35
43
  // 初始化 dirs:优先使用用户传入的 dirs,否则以 dir 为默认值,保证向后兼容
36
44
  if (!options.dirs) {
37
45
  options.dirs = [options.dir];
@@ -72,9 +80,11 @@ module.exports = fp(
72
80
  },
73
81
  start: true
74
82
  });
75
- //启动时,将running状态的任务设置为pending
83
+ // 启动时只恢复陈旧 running 任务,避免多实例部署时重置其他实例正在执行的任务
76
84
  fastify.addHook('onReady', async () => {
77
- await fastify[options.name].services.resetAll();
85
+ if (options.recoverRunningTasksOnStart) {
86
+ await fastify[options.name].services.resetAll({ staleOnly: true });
87
+ }
78
88
  });
79
89
  }
80
90
  })
@@ -52,6 +52,10 @@ module.exports = fp(async (fastify, options) => {
52
52
  maxRetries: {
53
53
  type: 'number',
54
54
  description: '最大自动重试次数,默认0'
55
+ },
56
+ timeout: {
57
+ type: 'number',
58
+ description: '任务超时时间(毫秒),0表示不超时,默认3600000ms'
55
59
  }
56
60
  },
57
61
  required: ['type', 'targetId', 'targetType']
@@ -90,9 +94,6 @@ module.exports = fp(async (fastify, options) => {
90
94
  targetId: {
91
95
  type: 'string'
92
96
  },
93
- targetName: {
94
- type: 'string'
95
- },
96
97
  type: {
97
98
  type: 'string'
98
99
  },
@@ -0,0 +1,556 @@
1
+ const path = require('node:path');
2
+ const fs = require('fs-extra');
3
+ const crypto = require('node:crypto');
4
+
5
+ const CONTEXT_KEY = Symbol.for('@kne/fastify-task.serviceContext');
6
+ const TERMINAL_STATUSES = ['success', 'failed', 'canceled'];
7
+ const ACTIVE_STATUSES = ['pending', 'running', 'waiting'];
8
+ const SCRIPT_NAME_REG = /^[A-Za-z0-9_-]+$/;
9
+
10
+ const createContext = (fastify, options) => {
11
+ const { models } = fastify[options.name];
12
+ const { Op } = fastify.sequelize.Sequelize;
13
+ const mainNamespace = options.name;
14
+ options.taskRegistry = options.taskRegistry || {};
15
+
16
+ const collectTaskStatistics = async task => {
17
+ if (task.reload && typeof task.reload === 'function') {
18
+ await task.reload();
19
+ }
20
+ const completedAt = task.completedAt || new Date();
21
+ const createdAt = task.createdAt;
22
+ const startedAt = task.startedAt;
23
+ let waitingTime = 0;
24
+ let executionTime = 0;
25
+ let totalTime = 0;
26
+ let hasTiming = false;
27
+
28
+ if (createdAt && completedAt) {
29
+ totalTime = new Date(completedAt).getTime() - new Date(createdAt).getTime();
30
+ if (startedAt) {
31
+ waitingTime = new Date(startedAt).getTime() - new Date(createdAt).getTime();
32
+ executionTime = new Date(completedAt).getTime() - new Date(startedAt).getTime();
33
+ } else {
34
+ executionTime = totalTime;
35
+ }
36
+ hasTiming = totalTime > 0;
37
+ }
38
+
39
+ const completedHour = new Date(completedAt).getHours();
40
+ const channel = `${task.type}:${task.runnerType || 'manual'}:${completedHour}`;
41
+ const status = task.status || 'unknown';
42
+
43
+ const data = { total: 1, [status]: 1 };
44
+ const unit = { total: 'count', [status]: 'count' };
45
+ if (hasTiming) {
46
+ Object.assign(data, { waitingTime, executionTime, totalTime });
47
+ Object.assign(unit, { waitingTime: 'ms', executionTime: 'ms', totalTime: 'ms' });
48
+ }
49
+ fastify[`${options.name}Statistics`].services
50
+ .collect({
51
+ channel,
52
+ data,
53
+ unit,
54
+ time: completedAt
55
+ })
56
+ .catch(e => {
57
+ fastify.log.error(`采集任务统计数据失败: ${e.message}`);
58
+ });
59
+ };
60
+
61
+ const generateSignature = ({ secret, id, data }) => {
62
+ const dataToSign = `${id}|${typeof data === 'string' ? data : JSON.stringify(data)}`;
63
+ const hmac = crypto.createHmac('sha256', secret);
64
+ hmac.update(dataToSign);
65
+ return hmac.digest('hex');
66
+ };
67
+
68
+ const verifySignature = ({ secret, id, data, signature }) => {
69
+ if (!secret) return true;
70
+ const expectedSignature = generateSignature({ secret, id, data });
71
+ if (typeof signature !== 'string' || signature.length !== expectedSignature.length) {
72
+ return false;
73
+ }
74
+ return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature));
75
+ };
76
+
77
+ const validateScriptName = scriptName => {
78
+ if (scriptName == null) return;
79
+ if (typeof scriptName !== 'string' || !SCRIPT_NAME_REG.test(scriptName)) {
80
+ throw new Error('scriptName 只能包含字母、数字、下划线或中划线');
81
+ }
82
+ };
83
+
84
+ const normalizeDirs = ({ dir, dirs } = {}) => {
85
+ const list = [];
86
+ if (dir) list.push(dir);
87
+ if (Array.isArray(dirs)) list.push(...dirs);
88
+ return [...new Set(list.filter(Boolean))];
89
+ };
90
+
91
+ const splitTaskName = type => {
92
+ const index = String(type || '').indexOf('.');
93
+ if (index === -1) {
94
+ return { namespace: null, taskName: type };
95
+ }
96
+ return {
97
+ namespace: String(type).slice(0, index),
98
+ taskName: String(type).slice(index + 1)
99
+ };
100
+ };
101
+
102
+ const getRegistryKey = ({ namespace, taskName }) => {
103
+ return namespace === mainNamespace ? taskName : `${namespace}.${taskName}`;
104
+ };
105
+
106
+ const normalizeTaskConfig = (taskName, config) => {
107
+ if (typeof config === 'function') {
108
+ return { handler: config };
109
+ }
110
+ if (config && typeof config === 'object' && !Array.isArray(config)) {
111
+ const { handler, errorHandler, next } = config;
112
+ if (handler != null && typeof handler !== 'function') {
113
+ throw new Error(`任务 ${taskName} 的 handler 必须是一个函数`);
114
+ }
115
+ if (errorHandler != null && typeof errorHandler !== 'function') {
116
+ throw new Error(`任务 ${taskName} 的 errorHandler 必须是一个函数`);
117
+ }
118
+ return { handler, errorHandler, next };
119
+ }
120
+ throw new Error(`任务 ${taskName} 的 handler 必须是一个函数`);
121
+ };
122
+
123
+ const registerTaskDeclaration = ({ namespace = mainNamespace, taskName, dirs, scriptName, config, override = false, syncLegacyTask = true, useGlobalDirs = false }) => {
124
+ const normalizedConfig = normalizeTaskConfig(taskName, config);
125
+ const registryKey = getRegistryKey({ namespace, taskName });
126
+ if (!override && options.taskRegistry[registryKey]) {
127
+ return { skipped: true, declaration: options.taskRegistry[registryKey] };
128
+ }
129
+ const declaration = {
130
+ namespace,
131
+ taskName,
132
+ type: registryKey,
133
+ dirs: dirs && dirs.length > 0 ? dirs : options.dirs,
134
+ useGlobalDirs,
135
+ scriptName: scriptName || (namespace === mainNamespace ? options.scriptName : 'index'),
136
+ handler: normalizedConfig.handler,
137
+ errorHandler: normalizedConfig.errorHandler,
138
+ next: normalizedConfig.next
139
+ };
140
+ options.taskRegistry[registryKey] = declaration;
141
+ if (syncLegacyTask && declaration.handler) {
142
+ options.task[registryKey] = declaration.handler;
143
+ if (namespace === mainNamespace) {
144
+ options.task[taskName] = declaration.handler;
145
+ }
146
+ }
147
+ return { skipped: false, declaration };
148
+ };
149
+
150
+ const getLegacyDeclaration = type => {
151
+ const config = options.task[type];
152
+ if (typeof config !== 'function' && !(config && typeof config === 'object' && !Array.isArray(config))) {
153
+ return null;
154
+ }
155
+ const { taskName } = splitTaskName(type);
156
+ return registerTaskDeclaration({
157
+ namespace: mainNamespace,
158
+ taskName,
159
+ dirs: options.dirs,
160
+ scriptName: options.scriptName,
161
+ config,
162
+ override: true,
163
+ syncLegacyTask: false,
164
+ useGlobalDirs: true
165
+ }).declaration;
166
+ };
167
+
168
+ Object.entries(options.task || {}).forEach(([type, config]) => {
169
+ if (typeof config === 'function' || (config && typeof config === 'object' && !Array.isArray(config))) {
170
+ const { taskName } = splitTaskName(type);
171
+ registerTaskDeclaration({
172
+ namespace: mainNamespace,
173
+ taskName,
174
+ dirs: options.dirs,
175
+ scriptName: options.scriptName,
176
+ config,
177
+ override: true,
178
+ syncLegacyTask: false,
179
+ useGlobalDirs: true
180
+ });
181
+ }
182
+ });
183
+
184
+ const resolveDeclarationByNamespace = ({ namespace, taskName }) => {
185
+ const registryKey = getRegistryKey({ namespace, taskName });
186
+ return options.taskRegistry[registryKey] || (namespace === mainNamespace ? getLegacyDeclaration(taskName) : null);
187
+ };
188
+
189
+ const resolveTaskDeclaration = (type, { currentDeclaration, forNext = false } = {}) => {
190
+ const { namespace, taskName } = splitTaskName(type);
191
+ if (namespace) {
192
+ if (forNext && currentDeclaration?.namespace !== mainNamespace && namespace === mainNamespace) {
193
+ throw new Error(`任务 ${currentDeclaration.type} 不允许访问主项目任务:${type}`);
194
+ }
195
+ return resolveDeclarationByNamespace({ namespace, taskName });
196
+ }
197
+
198
+ if (forNext && currentDeclaration) {
199
+ return resolveDeclarationByNamespace({ namespace: currentDeclaration.namespace, taskName });
200
+ }
201
+
202
+ const mainDeclaration = resolveDeclarationByNamespace({ namespace: mainNamespace, taskName });
203
+ if (mainDeclaration) return mainDeclaration;
204
+
205
+ const matchedDeclarations = Object.values(options.taskRegistry).filter(declaration => declaration.taskName === taskName);
206
+ if (matchedDeclarations.length === 1) {
207
+ return matchedDeclarations[0];
208
+ }
209
+ return options.taskRegistry[taskName] || getLegacyDeclaration(taskName);
210
+ };
211
+
212
+ const getTaskDeclaration = type => {
213
+ const declaration = resolveTaskDeclaration(type);
214
+ if (!declaration) {
215
+ throw new Error('未找到合法的任务声明');
216
+ }
217
+ return declaration;
218
+ };
219
+
220
+ const getTaskHandler = declaration => {
221
+ const legacyConfig = options.task[declaration.type] || (declaration.namespace === mainNamespace ? options.task[declaration.taskName] : null);
222
+ if (typeof legacyConfig === 'function') return legacyConfig;
223
+ if (legacyConfig && typeof legacyConfig === 'object' && typeof legacyConfig.handler === 'function') return legacyConfig.handler;
224
+ return declaration.handler;
225
+ };
226
+
227
+ const getTaskErrorHandler = declaration => {
228
+ const legacyConfig = options.task[declaration.type] || (declaration.namespace === mainNamespace ? options.task[declaration.taskName] : null);
229
+ if (legacyConfig && typeof legacyConfig === 'object' && typeof legacyConfig.errorHandler === 'function') return legacyConfig.errorHandler;
230
+ return declaration.errorHandler;
231
+ };
232
+
233
+ const getTaskNext = declaration => {
234
+ const legacyConfig = options.task[declaration.type] || (declaration.namespace === mainNamespace ? options.task[declaration.taskName] : null);
235
+ if (legacyConfig && typeof legacyConfig === 'object' && Object.prototype.hasOwnProperty.call(legacyConfig, 'next')) return legacyConfig.next;
236
+ return declaration.next;
237
+ };
238
+
239
+ const cloneJsonValue = value => {
240
+ if (value == null) return value;
241
+ return JSON.parse(JSON.stringify(value));
242
+ };
243
+
244
+ const normalizeError = error => {
245
+ if (error instanceof Error) {
246
+ return (error.stack || error.message || '').replaceAll(process.cwd(), '/server');
247
+ }
248
+ if (typeof error === 'string') {
249
+ return error.replaceAll(process.cwd(), '/server');
250
+ }
251
+ return error;
252
+ };
253
+
254
+ const detail = async ({ id }) => {
255
+ const task = await models.task.findByPk(id);
256
+ if (!task) {
257
+ throw new Error('任务不存在');
258
+ }
259
+ return task;
260
+ };
261
+
262
+ const isTerminalStatus = status => TERMINAL_STATUSES.includes(status);
263
+
264
+ const updateTaskByStatus = async ({ task, allowedStatuses = ACTIVE_STATUSES, updateData }) => {
265
+ const [affectedCount] = await models.task.update(updateData, {
266
+ where: {
267
+ id: task.id,
268
+ status: {
269
+ [Op.in]: allowedStatuses
270
+ }
271
+ }
272
+ });
273
+ if (affectedCount !== 1) {
274
+ if (task.reload && typeof task.reload === 'function') {
275
+ await task.reload();
276
+ }
277
+ return false;
278
+ }
279
+ if (task.reload && typeof task.reload === 'function') {
280
+ await task.reload();
281
+ }
282
+ return true;
283
+ };
284
+
285
+ const handleTaskError = async ({ task, error }) => {
286
+ const declaration = resolveTaskDeclaration(task.type);
287
+ let currentError = error;
288
+ const taskErrorHandler = declaration && getTaskErrorHandler(declaration);
289
+ if (typeof taskErrorHandler === 'function') {
290
+ try {
291
+ await taskErrorHandler({ task, error: currentError, context: task.context });
292
+ return;
293
+ } catch (e) {
294
+ currentError = e;
295
+ }
296
+ }
297
+
298
+ if (typeof options.errorHandler === 'function') {
299
+ try {
300
+ await options.errorHandler({ task, error: currentError, context: task.context });
301
+ } catch (e) {
302
+ fastify.log.error(e);
303
+ }
304
+ }
305
+ };
306
+
307
+ const failTask = async ({ task, error, updateData = {}, collect = true, allowedStatuses = ACTIVE_STATUSES }) => {
308
+ const transitioned = await updateTaskByStatus({
309
+ task,
310
+ allowedStatuses,
311
+ updateData: Object.assign({}, updateData, {
312
+ status: 'failed',
313
+ error: normalizeError(error),
314
+ completedAt: new Date(),
315
+ startedAt: task.startedAt || task.createdAt
316
+ })
317
+ });
318
+ if (!transitioned) {
319
+ return false;
320
+ }
321
+ await handleTaskError({ task, error });
322
+ if (collect) collectTaskStatistics(task);
323
+ return true;
324
+ };
325
+
326
+ 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
+ if (typeof delay !== 'number' || delay < 0) {
328
+ throw new Error('delay 必须为非负数');
329
+ }
330
+ if (typeof priority !== 'number' || !Number.isInteger(priority)) {
331
+ throw new Error('priority 必须为整数');
332
+ }
333
+ if (typeof maxRetries !== 'number' || !Number.isInteger(maxRetries) || maxRetries < 0) {
334
+ throw new Error('maxRetries 必须为非负整数');
335
+ }
336
+ if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout < 0) {
337
+ throw new Error('timeout 必须为非负整数');
338
+ }
339
+ validateScriptName(scriptName);
340
+ const declaration = getTaskDeclaration(type);
341
+ return await models.task.create({
342
+ userId,
343
+ input,
344
+ type: declaration.type,
345
+ targetId,
346
+ targetType,
347
+ runnerType,
348
+ priority,
349
+ parentTaskId,
350
+ maxRetries,
351
+ timeout,
352
+ startTime: delay > 0 ? new Date(Date.now() + 1000 * delay) : new Date(),
353
+ scriptName,
354
+ context,
355
+ options: currentOptions
356
+ });
357
+ };
358
+
359
+ const executor = async ({ type, scriptName, ...props }) => {
360
+ const declaration = getTaskDeclaration(type);
361
+ const currentScriptName = scriptName || declaration.scriptName || 'index';
362
+ validateScriptName(currentScriptName);
363
+ const scriptFile = `${currentScriptName}.js`;
364
+ let taskModulePath = null;
365
+ const dirs = declaration.useGlobalDirs ? options.dirs : declaration.dirs && declaration.dirs.length > 0 ? declaration.dirs : options.dirs;
366
+ for (const dir of dirs) {
367
+ const candidate = path.resolve(dir, declaration.taskName, scriptFile);
368
+ if (await fs.exists(candidate)) {
369
+ taskModulePath = candidate;
370
+ break;
371
+ }
372
+ }
373
+ if (!taskModulePath) {
374
+ throw new Error(`未匹配到任务执行器:${declaration.taskName}/${scriptFile},已搜索目录:${dirs.join(',')}`);
375
+ }
376
+ delete require.cache[taskModulePath];
377
+ return await require(taskModulePath)(fastify, options, {
378
+ ...props,
379
+ updateProgress: async progress => {
380
+ if (typeof props?.task?.update === 'function') {
381
+ await props.task.reload();
382
+ if (isTerminalStatus(props.task.status)) return;
383
+ await props.task.update({
384
+ progress: progress
385
+ });
386
+ }
387
+ },
388
+ polling: async (callback, currentOptions) => {
389
+ let pollCount = 0;
390
+ const maxPollTimes = currentOptions?.maxPollTimes || options.maxPollTimes;
391
+ const pollInterval = currentOptions?.pollInterval || options.pollInterval;
392
+ return await new Promise((resolve, reject) => {
393
+ const executePolling = async () => {
394
+ try {
395
+ pollCount++;
396
+ if (pollCount > maxPollTimes) {
397
+ reject(new Error(`轮询超时(${maxPollTimes}次),任务未完成`));
398
+ return;
399
+ }
400
+
401
+ const pollingResult = Object.assign({}, await callback());
402
+ const { result, data, message, progress } = pollingResult;
403
+
404
+ if (typeof props?.task?.update === 'function') {
405
+ await props.task.reload();
406
+ if (isTerminalStatus(props.task.status)) {
407
+ reject(new Error(`任务已结束:${props.task.status}`));
408
+ return;
409
+ }
410
+ await props.task.update(
411
+ Object.assign(
412
+ {},
413
+ {
414
+ pollCount: props.task.pollCount + 1,
415
+ pollResults: [...props.task.pollResults, Object.assign({}, pollingResult, { time: new Date() })]
416
+ },
417
+ Number.isInteger(progress) ? { progress } : {}
418
+ )
419
+ );
420
+ }
421
+
422
+ if (result === 'failed') {
423
+ reject(new Error(`任务处理失败:${message}`));
424
+ return;
425
+ }
426
+
427
+ if (result === 'success') {
428
+ resolve(data);
429
+ return;
430
+ }
431
+
432
+ setTimeout(executePolling, pollInterval);
433
+ } catch (e) {
434
+ reject(e);
435
+ }
436
+ };
437
+ setTimeout(executePolling, pollInterval);
438
+ });
439
+ },
440
+ next: async currentContext => {
441
+ if (typeof props?.task?.update === 'function') {
442
+ await props.task.reload();
443
+ if (isTerminalStatus(props.task.status)) return false;
444
+ await props.task.update({ context: currentContext, status: 'waiting' });
445
+ }
446
+ return false;
447
+ }
448
+ });
449
+ };
450
+
451
+ const resolveNextDeclaration = ({ declaration, output }) => {
452
+ const next = getTaskNext(declaration);
453
+ if (!next) return null;
454
+ let nextType;
455
+ if (typeof next === 'string') {
456
+ nextType = next;
457
+ } else if (Array.isArray(next)) {
458
+ nextType = output?.next;
459
+ if (!nextType) {
460
+ throw new Error(`任务 ${declaration.type} 未指定下一个任务`);
461
+ }
462
+ if (!next.includes(nextType)) {
463
+ throw new Error(`任务 ${declaration.type} 指定的下一个任务 ${nextType} 不在允许列表中`);
464
+ }
465
+ } else {
466
+ throw new Error(`任务 ${declaration.type} 的 next 配置必须是字符串或数组`);
467
+ }
468
+ const nextDeclaration = resolveTaskDeclaration(nextType, { currentDeclaration: declaration, forNext: true });
469
+ if (!nextDeclaration) {
470
+ throw new Error(`未找到下一个任务声明:${nextType}`);
471
+ }
472
+ return nextDeclaration;
473
+ };
474
+
475
+ const createNextTask = async ({ task, declaration, output }) => {
476
+ const nextDeclaration = resolveNextDeclaration({ declaration, output });
477
+ if (!nextDeclaration) return;
478
+ const input = output && typeof output === 'object' && !Array.isArray(output) ? cloneJsonValue(output) : { data: output };
479
+ if (task.input?.name != null) {
480
+ input.name = task.input.name;
481
+ }
482
+ await create({
483
+ userId: task.userId,
484
+ type: nextDeclaration.type,
485
+ targetId: task.id,
486
+ targetType: 'task',
487
+ runnerType: task.runnerType,
488
+ input,
489
+ context: cloneJsonValue(task.context || {}),
490
+ parentTaskId: task.id
491
+ });
492
+ };
493
+
494
+ const finalizeSuccess = async ({ task, output, handlerResult, userId, updateData = {} }) => {
495
+ const declaration = getTaskDeclaration(task.type);
496
+ const transitioned = await updateTaskByStatus({
497
+ task,
498
+ updateData: Object.assign({}, updateData, {
499
+ status: 'success',
500
+ output,
501
+ progress: 100,
502
+ completedAt: new Date(),
503
+ startedAt: task.startedAt || task.createdAt,
504
+ completedUserId: userId
505
+ })
506
+ });
507
+ if (!transitioned) {
508
+ return false;
509
+ }
510
+ const handler = getTaskHandler(declaration);
511
+ try {
512
+ if (typeof handler === 'function') {
513
+ await handler({ task, result: handlerResult === undefined ? output : handlerResult, context: task.context });
514
+ }
515
+ await createNextTask({ task, declaration, output });
516
+ } catch (e) {
517
+ await failTask({ task, error: e, updateData: { output, completedUserId: userId }, allowedStatuses: ['success'] });
518
+ throw e;
519
+ }
520
+ collectTaskStatistics(task);
521
+ await fastify[options.name].services.triggerChildTasks(task);
522
+ return true;
523
+ };
524
+
525
+ return {
526
+ fastify,
527
+ options,
528
+ models,
529
+ Op,
530
+ mainNamespace,
531
+ collectTaskStatistics,
532
+ verifySignature,
533
+ validateScriptName,
534
+ isTerminalStatus,
535
+ updateTaskByStatus,
536
+ normalizeDirs,
537
+ registerTaskDeclaration,
538
+ getTaskDeclaration,
539
+ resolveTaskDeclaration,
540
+ detail,
541
+ failTask,
542
+ create,
543
+ executor,
544
+ finalizeSuccess
545
+ };
546
+ };
547
+
548
+ const getTaskServiceContext = (fastify, options) => {
549
+ const namespace = fastify[options.name];
550
+ if (!namespace[CONTEXT_KEY]) {
551
+ namespace[CONTEXT_KEY] = createContext(fastify, options);
552
+ }
553
+ return namespace[CONTEXT_KEY];
554
+ };
555
+
556
+ module.exports = getTaskServiceContext;
@@ -43,10 +43,15 @@ module.exports = ({ DataTypes, definePrimaryType, options }) => {
43
43
  comment: '最大重试次数,0表示不自动重试',
44
44
  defaultValue: 0
45
45
  },
46
+ timeout: {
47
+ type: DataTypes.INTEGER,
48
+ comment: '任务超时时间(毫秒),0表示不超时,默认3600000ms',
49
+ defaultValue: 60 * 60 * 1000
50
+ },
46
51
  startTime: {
47
52
  type: DataTypes.DATE,
48
53
  comment: '任务最早执行时间',
49
- defaultValue: new Date()
54
+ defaultValue: DataTypes.NOW
50
55
  },
51
56
  startedAt: {
52
57
  type: DataTypes.DATE,
@@ -0,0 +1,45 @@
1
+ const fp = require('fastify-plugin');
2
+ const fs = require('fs-extra');
3
+ const getTaskServiceContext = require('../helpers/task-service-context');
4
+
5
+ module.exports = fp(async (fastify, options) => {
6
+ const context = getTaskServiceContext(fastify, options);
7
+
8
+ const append = async ({ name = context.mainNamespace, dir, dirs, scriptName, tasks, override = false }) => {
9
+ const appendDirs = context.normalizeDirs({ dir, dirs });
10
+ const result = { dirs: [], tasks: [], skippedTasks: [] };
11
+ for (const currentDir of appendDirs) {
12
+ if (!options.dirs.includes(currentDir)) {
13
+ if (!(await fs.exists(currentDir))) {
14
+ console.warn(`append 目录不存在:${currentDir},仍会添加但运行时可能无法匹配任务执行器`);
15
+ }
16
+ // 保持旧 API 可见性;执行器会优先使用任务声明自己的 dirs。
17
+ options.dirs.push(currentDir);
18
+ result.dirs.push(currentDir);
19
+ }
20
+ }
21
+ if (tasks && typeof tasks === 'object') {
22
+ Object.entries(tasks).forEach(([taskName, config]) => {
23
+ const { skipped, declaration } = context.registerTaskDeclaration({
24
+ namespace: name,
25
+ taskName,
26
+ dirs: appendDirs.length > 0 ? appendDirs : options.dirs,
27
+ scriptName: scriptName || 'index',
28
+ config,
29
+ override,
30
+ syncLegacyTask: true
31
+ });
32
+ if (skipped) {
33
+ result.skippedTasks.push(declaration.type);
34
+ return;
35
+ }
36
+ result.tasks.push(declaration.type);
37
+ });
38
+ }
39
+ return result;
40
+ };
41
+
42
+ Object.assign(fastify[options.name].services, {
43
+ append
44
+ });
45
+ });