@kne/fastify-task 2.0.2 → 2.0.3

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.
@@ -2,17 +2,15 @@ const fp = require('fastify-plugin');
2
2
  const path = require('node:path');
3
3
  const fs = require('fs-extra');
4
4
  const crypto = require('node:crypto');
5
- const dayjs = require('dayjs');
6
- const utc = require('dayjs/plugin/utc');
7
- const timezone = require('dayjs/plugin/timezone');
8
-
9
- dayjs.extend(utc);
10
- dayjs.extend(timezone);
11
5
 
12
6
  module.exports = fp(async (fastify, options) => {
13
7
  const { models } = fastify[options.name];
14
8
  const { Op } = fastify.sequelize.Sequelize;
15
9
 
10
+ /** statistics 插件在 main 之后注册,不能在初始化时解构,否则恒为 undefined */
11
+ const callFlushCompletionStatistics = task =>
12
+ fastify[options.name].services.flushCompletionStatistics?.(task);
13
+
16
14
  const generateSignature = ({ secret, id, data }) => {
17
15
  const dataToSign = `${id}|${typeof data === 'string' ? data : JSON.stringify(data)}`;
18
16
  const hmac = crypto.createHmac('sha256', secret);
@@ -143,7 +141,7 @@ module.exports = fp(async (fastify, options) => {
143
141
  error: result,
144
142
  completedAt: new Date()
145
143
  });
146
- updateDailyStatistics(task);
144
+ callFlushCompletionStatistics(task);
147
145
  return;
148
146
  }
149
147
  await options.task[task.type]({ task, result: result.data, context: task.context });
@@ -153,7 +151,7 @@ module.exports = fp(async (fastify, options) => {
153
151
  progress: 100,
154
152
  completedAt: new Date()
155
153
  });
156
- updateDailyStatistics(task);
154
+ callFlushCompletionStatistics(task);
157
155
  };
158
156
 
159
157
  const processSystemTask = async task => {
@@ -184,7 +182,7 @@ module.exports = fp(async (fastify, options) => {
184
182
  progress: 100,
185
183
  completedAt: new Date()
186
184
  });
187
- updateDailyStatistics(task);
185
+ callFlushCompletionStatistics(task);
188
186
  })
189
187
  .catch(async e => {
190
188
  await task.update({
@@ -192,7 +190,7 @@ module.exports = fp(async (fastify, options) => {
192
190
  error: (e.stack || '').replaceAll(process.cwd(), '/server'),
193
191
  completedAt: new Date()
194
192
  });
195
- updateDailyStatistics(task);
193
+ callFlushCompletionStatistics(task);
196
194
  });
197
195
  } catch (e) {
198
196
  await task.update({
@@ -200,7 +198,7 @@ module.exports = fp(async (fastify, options) => {
200
198
  error: (e.stack || '').replaceAll(process.cwd(), '/server'),
201
199
  completedAt: new Date()
202
200
  });
203
- updateDailyStatistics(task);
201
+ callFlushCompletionStatistics(task);
204
202
  }
205
203
  };
206
204
 
@@ -250,21 +248,28 @@ module.exports = fp(async (fastify, options) => {
250
248
 
251
249
  const cancel = async ({ id, targetId, targetType, type }) => {
252
250
  if (targetId && targetType && type) {
251
+ const bulkWhere = {
252
+ targetId,
253
+ targetType,
254
+ type,
255
+ status: {
256
+ [Op.in]: ['pending', 'running']
257
+ }
258
+ };
259
+ const tasksToCancel = await models.task.findAll({ where: bulkWhere, raw: true });
260
+ const completedAt = new Date();
253
261
  const [affectedCount] = await models.task.update(
254
262
  {
255
- status: 'canceled'
263
+ status: 'canceled',
264
+ completedAt
256
265
  },
257
266
  {
258
- where: {
259
- targetId,
260
- targetType,
261
- type,
262
- status: {
263
- [Op.in]: ['pending', 'running']
264
- }
265
- }
267
+ where: bulkWhere
266
268
  }
267
269
  );
270
+ for (const row of tasksToCancel) {
271
+ callFlushCompletionStatistics(Object.assign({}, row, { status: 'canceled', completedAt }));
272
+ }
268
273
  return affectedCount;
269
274
  }
270
275
  if (id) {
@@ -276,7 +281,7 @@ module.exports = fp(async (fastify, options) => {
276
281
  status: 'canceled',
277
282
  completedAt: new Date()
278
283
  });
279
- updateDailyStatistics(task);
284
+ callFlushCompletionStatistics(task);
280
285
  }
281
286
  };
282
287
 
@@ -296,7 +301,7 @@ module.exports = fp(async (fastify, options) => {
296
301
  startedAt: task.startedAt || task.createdAt,
297
302
  completedUserId: userId
298
303
  });
299
- updateDailyStatistics(task);
304
+ callFlushCompletionStatistics(task);
300
305
  } catch (e) {
301
306
  await task.update(
302
307
  Object.assign({}, props, {
@@ -307,7 +312,7 @@ module.exports = fp(async (fastify, options) => {
307
312
  startedAt: task.startedAt || task.createdAt
308
313
  })
309
314
  );
310
- updateDailyStatistics(task);
315
+ callFlushCompletionStatistics(task);
311
316
  throw e;
312
317
  }
313
318
  } else {
@@ -319,7 +324,7 @@ module.exports = fp(async (fastify, options) => {
319
324
  completedUserId: userId
320
325
  })
321
326
  );
322
- updateDailyStatistics(task);
327
+ callFlushCompletionStatistics(task);
323
328
  }
324
329
  };
325
330
 
@@ -539,692 +544,6 @@ module.exports = fp(async (fastify, options) => {
539
544
  return callback({ id, code, data, message });
540
545
  };
541
546
 
542
- // 按指定时区获取"今天0点"的UTC Date对象
543
- const getTodayStart = tz => {
544
- if (!tz) {
545
- return dayjs().startOf('day').toDate();
546
- }
547
- return dayjs().tz(tz).startOf('day').toDate();
548
- };
549
-
550
- // 按指定时区格式化日期
551
- const formatDate = (date, tz) => {
552
- if (!tz) {
553
- return dayjs(date).format('YYYY-MM-DD');
554
- }
555
- return dayjs(date).tz(tz).format('YYYY-MM-DD');
556
- };
557
-
558
- const resolveTimezone = tz => tz || dayjs.tz.guess();
559
-
560
- /** 与 updateDailyStatistics 一致的耗时计算(用于实时接口在无日统计时的回算) */
561
- const computeTaskTiming = task => {
562
- const completedAt = task.completedAt ? new Date(task.completedAt) : null;
563
- const createdAt = task.createdAt ? new Date(task.createdAt) : null;
564
- const startedAt = task.startedAt ? new Date(task.startedAt) : null;
565
- let waitingTime = 0;
566
- let executionTime = 0;
567
- let totalTime = 0;
568
- let hasTiming = false;
569
- if (createdAt && completedAt && !Number.isNaN(createdAt.getTime()) && !Number.isNaN(completedAt.getTime())) {
570
- totalTime = completedAt.getTime() - createdAt.getTime();
571
- if (startedAt && !Number.isNaN(startedAt.getTime())) {
572
- waitingTime = startedAt.getTime() - createdAt.getTime();
573
- executionTime = completedAt.getTime() - startedAt.getTime();
574
- } else {
575
- executionTime = totalTime;
576
- }
577
- hasTiming = totalTime > 0;
578
- }
579
- return { waitingTime, executionTime, totalTime, hasTiming };
580
- };
581
-
582
- // 更新每日统计表(任务完成/取消时调用,异步不阻塞主流程)
583
- const updateDailyStatistics = task => {
584
- const completedAt = task.completedAt || new Date();
585
- const statDate = dayjs(completedAt).format('YYYY-MM-DD');
586
- const status = task.status;
587
-
588
- // 计算耗时
589
- const createdAt = task.createdAt;
590
- const startedAt = task.startedAt;
591
- let waitingTime = 0;
592
- let executionTime = 0;
593
- let totalTime = 0;
594
- let hasTiming = false;
595
-
596
- if (createdAt && completedAt) {
597
- totalTime = new Date(completedAt).getTime() - new Date(createdAt).getTime();
598
- if (startedAt) {
599
- waitingTime = new Date(startedAt).getTime() - new Date(createdAt).getTime();
600
- executionTime = new Date(completedAt).getTime() - new Date(startedAt).getTime();
601
- } else {
602
- // 无startedAt时(手动任务直接完成),等待时间=0,执行时间=总耗时
603
- executionTime = totalTime;
604
- }
605
- hasTiming = totalTime > 0;
606
- }
607
-
608
- // 异步更新,不阻塞主流程
609
- (async () => {
610
- try {
611
- const [stat, created] = await models.taskDailyStatistics.findOrCreate({
612
- where: { date: statDate },
613
- defaults: {
614
- date: statDate,
615
- totalCompleted: 1,
616
- successCount: status === 'success' ? 1 : 0,
617
- failedCount: status === 'failed' ? 1 : 0,
618
- canceledCount: status === 'canceled' ? 1 : 0,
619
- totalWaitingTime: hasTiming ? waitingTime : 0,
620
- totalExecutionTime: hasTiming ? executionTime : 0,
621
- totalTime: hasTiming ? totalTime : 0,
622
- timedTaskCount: hasTiming ? 1 : 0,
623
- byType: {
624
- [task.type]: {
625
- count: 1,
626
- successCount: status === 'success' ? 1 : 0,
627
- failedCount: status === 'failed' ? 1 : 0,
628
- canceledCount: status === 'canceled' ? 1 : 0,
629
- totalWaitingTime: hasTiming ? waitingTime : 0,
630
- totalExecutionTime: hasTiming ? executionTime : 0,
631
- totalTime: hasTiming ? totalTime : 0,
632
- timedTaskCount: hasTiming ? 1 : 0
633
- }
634
- },
635
- byRunnerType: {
636
- [task.runnerType]: {
637
- count: 1,
638
- successCount: status === 'success' ? 1 : 0,
639
- failedCount: status === 'failed' ? 1 : 0,
640
- canceledCount: status === 'canceled' ? 1 : 0,
641
- totalWaitingTime: hasTiming ? waitingTime : 0,
642
- totalExecutionTime: hasTiming ? executionTime : 0,
643
- totalTime: hasTiming ? totalTime : 0,
644
- timedTaskCount: hasTiming ? 1 : 0
645
- }
646
- }
647
- }
648
- });
649
-
650
- if (!created) {
651
- const mergeKey = (obj, key, increment) => {
652
- const current = obj[key] || {
653
- count: 0, successCount: 0, failedCount: 0, canceledCount: 0,
654
- totalWaitingTime: 0, totalExecutionTime: 0, totalTime: 0, timedTaskCount: 0
655
- };
656
- return Object.assign({}, obj, {
657
- [key]: {
658
- count: current.count + (increment.count || 0),
659
- successCount: current.successCount + (increment.successCount || 0),
660
- failedCount: current.failedCount + (increment.failedCount || 0),
661
- canceledCount: current.canceledCount + (increment.canceledCount || 0),
662
- totalWaitingTime: current.totalWaitingTime + (increment.totalWaitingTime || 0),
663
- totalExecutionTime: current.totalExecutionTime + (increment.totalExecutionTime || 0),
664
- totalTime: current.totalTime + (increment.totalTime || 0),
665
- timedTaskCount: current.timedTaskCount + (increment.timedTaskCount || 0)
666
- }
667
- });
668
- };
669
-
670
- const typeIncrement = {
671
- count: 1,
672
- successCount: status === 'success' ? 1 : 0,
673
- failedCount: status === 'failed' ? 1 : 0,
674
- canceledCount: status === 'canceled' ? 1 : 0,
675
- totalWaitingTime: hasTiming ? waitingTime : 0,
676
- totalExecutionTime: hasTiming ? executionTime : 0,
677
- totalTime: hasTiming ? totalTime : 0,
678
- timedTaskCount: hasTiming ? 1 : 0
679
- };
680
-
681
- await stat.update({
682
- totalCompleted: stat.totalCompleted + 1,
683
- successCount: stat.successCount + (status === 'success' ? 1 : 0),
684
- failedCount: stat.failedCount + (status === 'failed' ? 1 : 0),
685
- canceledCount: stat.canceledCount + (status === 'canceled' ? 1 : 0),
686
- totalWaitingTime: stat.totalWaitingTime + (hasTiming ? waitingTime : 0),
687
- totalExecutionTime: stat.totalExecutionTime + (hasTiming ? executionTime : 0),
688
- totalTime: stat.totalTime + (hasTiming ? totalTime : 0),
689
- timedTaskCount: stat.timedTaskCount + (hasTiming ? 1 : 0),
690
- byType: mergeKey(stat.byType || {}, task.type, typeIncrement),
691
- byRunnerType: mergeKey(stat.byRunnerType || {}, task.runnerType, typeIncrement)
692
- });
693
- }
694
- } catch (e) {
695
- fastify.log.error(`更新每日统计失败: ${e.message}`);
696
- }
697
- })();
698
- };
699
-
700
- const statistics = {
701
- getOverview: async ({ range = '7d', timezone, type, runnerType } = {}) => {
702
- const { Sequelize } = models.task.sequelize;
703
- const taskModel = models.task;
704
- const createdAtCol = taskModel.rawAttributes.createdAt.field;
705
- const dialect = taskModel.sequelize.getDialect();
706
- const effectiveTimezone = resolveTimezone(timezone);
707
-
708
- const rangeMap = {
709
- '7d': { days: 7, label: '近7天' },
710
- '1m': { days: 30, label: '近1个月' },
711
- '1y': { days: 365, label: '近1年' }
712
- };
713
- const normalizedRange = rangeMap[range] ? range : '7d';
714
- const rangeConfig = rangeMap[normalizedRange];
715
- const todayStart = getTodayStart(effectiveTimezone);
716
- const startDate = new Date(todayStart);
717
- startDate.setDate(startDate.getDate() - rangeConfig.days);
718
-
719
- const whereRange = { createdAt: { [Sequelize.Op.gte]: startDate } };
720
- if (type) {
721
- whereRange.type = type;
722
- }
723
- if (runnerType) {
724
- whereRange.runnerType = runnerType;
725
- }
726
-
727
- // 按时区格式化日期的SQL
728
- const dateFn = (() => {
729
- if (!effectiveTimezone || dialect === 'sqlite') {
730
- return col => Sequelize.fn('DATE', Sequelize.col(col));
731
- }
732
- if (dialect === 'postgres') {
733
- return col => Sequelize.fn('TO_CHAR', Sequelize.literal(`"${col}" AT TIME ZONE '${effectiveTimezone}'`), 'YYYY-MM-DD');
734
- }
735
- return col => Sequelize.fn('DATE_FORMAT', Sequelize.fn('CONVERT_TZ', Sequelize.col(col), '+00:00', Sequelize.literal(`'${effectiveTimezone}'`)), '%Y-%m-%d');
736
- })();
737
-
738
- // 并行执行所有查询
739
- const [totalTasks, byStatus, byType, byRunnerType, byTargetType, recentTrend, recentTrendByStatus, recentTrendByType] = await Promise.all([
740
- taskModel.count({ where: whereRange }),
741
- taskModel.findAll({
742
- attributes: ['status', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
743
- where: whereRange,
744
- group: ['status'],
745
- raw: true
746
- }),
747
- taskModel.findAll({
748
- attributes: ['type', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
749
- where: whereRange,
750
- group: ['type'],
751
- raw: true
752
- }),
753
- taskModel.findAll({
754
- attributes: ['runnerType', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
755
- where: whereRange,
756
- group: ['runnerType'],
757
- raw: true
758
- }),
759
- taskModel.findAll({
760
- attributes: ['targetType', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
761
- where: whereRange,
762
- group: ['targetType'],
763
- raw: true
764
- }),
765
- taskModel.findAll({
766
- attributes: [
767
- [dateFn(createdAtCol), 'date'],
768
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
769
- ],
770
- where: whereRange,
771
- group: [dateFn(createdAtCol)],
772
- order: [[dateFn(createdAtCol), 'ASC']],
773
- raw: true
774
- }),
775
- taskModel.findAll({
776
- attributes: [
777
- [dateFn(createdAtCol), 'date'],
778
- 'status',
779
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
780
- ],
781
- where: whereRange,
782
- group: [dateFn(createdAtCol), 'status'],
783
- order: [[dateFn(createdAtCol), 'ASC']],
784
- raw: true
785
- }),
786
- taskModel.findAll({
787
- attributes: [
788
- [dateFn(createdAtCol), 'date'],
789
- 'type',
790
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
791
- ],
792
- where: whereRange,
793
- group: [dateFn(createdAtCol), 'type'],
794
- order: [[dateFn(createdAtCol), 'ASC']],
795
- raw: true
796
- })
797
- ]);
798
-
799
- // SQLite 需要在JS层做时区偏移修正DATE结果
800
- const adjustDate = dateStr => {
801
- if (!effectiveTimezone || dialect !== 'sqlite') return dateStr;
802
- return dayjs.utc(dateStr).tz(effectiveTimezone).format('YYYY-MM-DD');
803
- };
804
-
805
- // 从预聚合表读取每日耗时统计
806
- const dailyStats = await models.taskDailyStatistics.findAll({
807
- where: { date: { [Sequelize.Op.gte]: dayjs(startDate).format('YYYY-MM-DD') } },
808
- order: [['date', 'ASC']],
809
- raw: true
810
- });
811
-
812
- const durationTrend = dailyStats.map(item => {
813
- // 如果指定了type/runnerType筛选,从对应子维度中提取数据作为主数据
814
- const typeData = type && item.byType && item.byType[type] ? item.byType[type] : null;
815
- const runnerTypeData = runnerType && item.byRunnerType && item.byRunnerType[runnerType] ? item.byRunnerType[runnerType] : null;
816
- // runnerType优先级高于type(两者同时指定时取交集,但预聚合表无交叉维度,取runnerType)
817
- const filterData = runnerTypeData || typeData;
818
- const mainTimedTaskCount = filterData ? filterData.timedTaskCount : item.timedTaskCount;
819
- const mainTotalWaitingTime = filterData ? filterData.totalWaitingTime : item.totalWaitingTime;
820
- const mainTotalExecutionTime = filterData ? filterData.totalExecutionTime : item.totalExecutionTime;
821
- const mainTotalTime = filterData ? filterData.totalTime : item.totalTime;
822
-
823
- return {
824
- date: item.date,
825
- completedCount: filterData ? filterData.count : item.totalCompleted,
826
- successCount: filterData ? filterData.successCount : item.successCount,
827
- failedCount: filterData ? filterData.failedCount : item.failedCount,
828
- canceledCount: filterData ? filterData.canceledCount : item.canceledCount,
829
- avgWaitingTime: mainTimedTaskCount > 0 ? Math.round(mainTotalWaitingTime / mainTimedTaskCount) : 0,
830
- avgExecutionTime: mainTimedTaskCount > 0 ? Math.round(mainTotalExecutionTime / mainTimedTaskCount) : 0,
831
- avgTotalTime: mainTimedTaskCount > 0 ? Math.round(mainTotalTime / mainTimedTaskCount) : 0,
832
- byType: Object.entries(item.byType || {}).reduce((acc, [key, val]) => {
833
- if (type && key !== type) return acc;
834
- acc[key] = {
835
- count: val.count,
836
- avgWaitingTime: val.timedTaskCount > 0 ? Math.round(val.totalWaitingTime / val.timedTaskCount) : 0,
837
- avgExecutionTime: val.timedTaskCount > 0 ? Math.round(val.totalExecutionTime / val.timedTaskCount) : 0,
838
- avgTotalTime: val.timedTaskCount > 0 ? Math.round(val.totalTime / val.timedTaskCount) : 0
839
- };
840
- return acc;
841
- }, {}),
842
- byRunnerType: Object.entries(item.byRunnerType || {}).reduce((acc, [key, val]) => {
843
- if (runnerType && key !== runnerType) return acc;
844
- acc[key] = {
845
- count: val.count,
846
- avgWaitingTime: val.timedTaskCount > 0 ? Math.round(val.totalWaitingTime / val.timedTaskCount) : 0,
847
- avgExecutionTime: val.timedTaskCount > 0 ? Math.round(val.totalExecutionTime / val.timedTaskCount) : 0,
848
- avgTotalTime: val.timedTaskCount > 0 ? Math.round(val.totalTime / val.timedTaskCount) : 0
849
- };
850
- return acc;
851
- }, {})
852
- };
853
- });
854
-
855
- return {
856
- range: normalizedRange,
857
- rangeLabel: rangeConfig.label,
858
- totalTasks,
859
- byStatus: byStatus.reduce((acc, item) => {
860
- acc[item.status] = Number(item.count);
861
- return acc;
862
- }, {}),
863
- byType: byType.reduce((acc, item) => {
864
- acc[item.type] = Number(item.count);
865
- return acc;
866
- }, {}),
867
- byRunnerType: byRunnerType.reduce((acc, item) => {
868
- acc[item.runnerType] = Number(item.count);
869
- return acc;
870
- }, {}),
871
- byTargetType: byTargetType.reduce((acc, item) => {
872
- acc[item.targetType] = Number(item.count);
873
- return acc;
874
- }, {}),
875
- recentTrend: recentTrend.map(item => ({ date: adjustDate(item.date), count: Number(item.count) })),
876
- recentTrendByStatus: recentTrendByStatus.map(item => ({ date: adjustDate(item.date), status: item.status, count: Number(item.count) })),
877
- recentTrendByType: recentTrendByType.map(item => ({ date: adjustDate(item.date), type: item.type, count: Number(item.count) })),
878
- durationTrend
879
- };
880
- },
881
-
882
- getRealtime: async ({ timezone, type, runnerType } = {}) => {
883
- const { Sequelize } = models.task.sequelize;
884
- const taskModel = models.task;
885
- const createdAtCol = taskModel.rawAttributes.createdAt.field;
886
- const dialect = taskModel.sequelize.getDialect();
887
- const effectiveTimezone = resolveTimezone(timezone);
888
-
889
- const todayStart = getTodayStart(effectiveTimezone);
890
- const whereToday = { createdAt: { [Sequelize.Op.gte]: todayStart } };
891
- if (type) {
892
- whereToday.type = type;
893
- }
894
- if (runnerType) {
895
- whereToday.runnerType = runnerType;
896
- }
897
-
898
- // 按小时提取
899
- const hourExtract = (() => {
900
- if (!effectiveTimezone || dialect === 'sqlite') {
901
- return dialect === 'sqlite'
902
- ? Sequelize.fn('strftime', '%H', Sequelize.col(createdAtCol))
903
- : Sequelize.fn('EXTRACT', Sequelize.literal(`HOUR FROM "${createdAtCol}"`));
904
- }
905
- if (dialect === 'postgres') {
906
- return Sequelize.fn('EXTRACT', Sequelize.literal(`HOUR FROM "${createdAtCol}" AT TIME ZONE '${effectiveTimezone}'`));
907
- }
908
- return Sequelize.fn('EXTRACT', Sequelize.literal(`HOUR FROM CONVERT_TZ("${createdAtCol}", '+00:00', '${effectiveTimezone}')`));
909
- })();
910
-
911
- // 15分钟间隔提取
912
- const intervalExtract = (() => {
913
- if (dialect === 'sqlite') {
914
- return Sequelize.literal(`strftime('%H', "${createdAtCol}") || ':' || printf('%02d', CAST(strftime('%M', "${createdAtCol}") AS INTEGER) / 15 * 15)`);
915
- }
916
- if (!effectiveTimezone) {
917
- if (dialect === 'postgres') {
918
- return Sequelize.literal(`TO_CHAR("${createdAtCol}", 'HH24:') || LPAD((FLOOR(EXTRACT(MINUTE FROM "${createdAtCol}") / 15) * 15)::TEXT, 2, '0')`);
919
- }
920
- return Sequelize.literal(`CONCAT(DATE_FORMAT("${createdAtCol}", '%H:'), LPAD(FLOOR(EXTRACT(MINUTE FROM "${createdAtCol}") / 15) * 15, 2, '0'))`);
921
- }
922
- if (dialect === 'postgres') {
923
- return Sequelize.literal(`TO_CHAR("${createdAtCol}" AT TIME ZONE '${effectiveTimezone}', 'HH24:') || LPAD((FLOOR(EXTRACT(MINUTE FROM "${createdAtCol}" AT TIME ZONE '${effectiveTimezone}') / 15) * 15)::TEXT, 2, '0')`);
924
- }
925
- return Sequelize.literal(`CONCAT(DATE_FORMAT(CONVERT_TZ("${createdAtCol}", '+00:00', '${effectiveTimezone}'), '%H:'), LPAD(FLOOR(EXTRACT(MINUTE FROM CONVERT_TZ("${createdAtCol}", '+00:00', '${effectiveTimezone}')) / 15) * 15, 2, '0'))`);
926
- })();
927
-
928
- const [totalTasks, byStatus, byType, byRunnerType, pendingByRunnerType, nonPendingByRunnerType, hourlyTrend, hourlyTrendByStatus, hourlyTrendByType, intervalTrend] = await Promise.all([
929
- taskModel.count({ where: whereToday }),
930
- taskModel.findAll({
931
- attributes: ['status', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
932
- where: whereToday,
933
- group: ['status'],
934
- raw: true
935
- }),
936
- taskModel.findAll({
937
- attributes: ['type', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
938
- where: whereToday,
939
- group: ['type'],
940
- raw: true
941
- }),
942
- taskModel.findAll({
943
- attributes: ['runnerType', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
944
- where: whereToday,
945
- group: ['runnerType'],
946
- raw: true
947
- }),
948
- taskModel.findAll({
949
- attributes: ['runnerType', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
950
- where: { ...whereToday, status: 'pending' },
951
- group: ['runnerType'],
952
- raw: true
953
- }),
954
- taskModel.findAll({
955
- attributes: ['runnerType', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
956
- where: { ...whereToday, status: { [Sequelize.Op.ne]: 'pending' } },
957
- group: ['runnerType'],
958
- raw: true
959
- }),
960
- taskModel.findAll({
961
- attributes: [
962
- [hourExtract, 'hour'],
963
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
964
- ],
965
- where: whereToday,
966
- group: [hourExtract],
967
- order: [[hourExtract, 'ASC']],
968
- raw: true
969
- }),
970
- taskModel.findAll({
971
- attributes: [
972
- [hourExtract, 'hour'],
973
- 'status',
974
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
975
- ],
976
- where: whereToday,
977
- group: [hourExtract, 'status'],
978
- order: [[hourExtract, 'ASC'], ['status', 'ASC']],
979
- raw: true
980
- }),
981
- taskModel.findAll({
982
- attributes: [
983
- [hourExtract, 'hour'],
984
- 'type',
985
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
986
- ],
987
- where: whereToday,
988
- group: [hourExtract, 'type'],
989
- order: [[hourExtract, 'ASC'], ['type', 'ASC']],
990
- raw: true
991
- }),
992
- taskModel.findAll({
993
- attributes: [
994
- [intervalExtract, 'interval'],
995
- [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
996
- ],
997
- where: whereToday,
998
- group: [intervalExtract],
999
- order: [[intervalExtract, 'ASC']],
1000
- raw: true
1001
- })
1002
- ]);
1003
-
1004
- // SQLite的hour/interval是UTC,需按timezone偏移修正
1005
- const adjustHour = hour => {
1006
- if (!effectiveTimezone || dialect !== 'sqlite') return Number(hour);
1007
- const utcTime = dayjs.utc().startOf('day').hour(Number(hour));
1008
- return utcTime.tz(effectiveTimezone).hour();
1009
- };
1010
-
1011
- const adjustInterval = intervalStr => {
1012
- if (!effectiveTimezone || dialect !== 'sqlite') return intervalStr;
1013
- const [h, m] = intervalStr.split(':').map(Number);
1014
- const utcTime = dayjs.utc().startOf('day').hour(h).minute(m);
1015
- return utcTime.tz(effectiveTimezone).format('HH:mm');
1016
- };
1017
-
1018
- const byRunnerTypeMap = byRunnerType.reduce((acc, item) => {
1019
- acc[item.runnerType] = Number(item.count);
1020
- return acc;
1021
- }, {});
1022
- const pendingByRunnerTypeMap = pendingByRunnerType.reduce((acc, item) => {
1023
- acc[item.runnerType] = Number(item.count);
1024
- return acc;
1025
- }, {});
1026
- const nonPendingByRunnerTypeMap = nonPendingByRunnerType.reduce((acc, item) => {
1027
- acc[item.runnerType] = Number(item.count);
1028
- return acc;
1029
- }, {});
1030
- const runnerTypeStatsKeys = new Set([
1031
- ...Object.keys(byRunnerTypeMap),
1032
- ...Object.keys(pendingByRunnerTypeMap),
1033
- ...Object.keys(nonPendingByRunnerTypeMap)
1034
- ]);
1035
- const runnerTypeStats = {};
1036
- for (const k of runnerTypeStatsKeys) {
1037
- runnerTypeStats[k] = {
1038
- total: Number(byRunnerTypeMap[k]) || 0,
1039
- pending: Number(pendingByRunnerTypeMap[k]) || 0,
1040
- executed: Number(nonPendingByRunnerTypeMap[k]) || 0
1041
- };
1042
- }
1043
-
1044
- return {
1045
- date: formatDate(todayStart, effectiveTimezone),
1046
- totalTasks,
1047
- byStatus: byStatus.reduce((acc, item) => {
1048
- acc[item.status] = Number(item.count);
1049
- return acc;
1050
- }, {}),
1051
- byType: byType.reduce((acc, item) => {
1052
- acc[item.type] = Number(item.count);
1053
- return acc;
1054
- }, {}),
1055
- byRunnerType: byRunnerTypeMap,
1056
- pendingByRunnerType: pendingByRunnerTypeMap,
1057
- runnerTypeStats,
1058
- hourlyTrend: hourlyTrend.map(item => ({ hour: adjustHour(item.hour), count: Number(item.count) })),
1059
- hourlyTrendByStatus: hourlyTrendByStatus.map(item => ({
1060
- hour: adjustHour(item.hour),
1061
- status: item.status,
1062
- count: Number(item.count)
1063
- })),
1064
- hourlyTrendByType: hourlyTrendByType.map(item => ({
1065
- hour: adjustHour(item.hour),
1066
- type: item.type,
1067
- count: Number(item.count)
1068
- })),
1069
- intervalTrend: intervalTrend.map(item => ({ interval: adjustInterval(item.interval), count: Number(item.count) })),
1070
- todayDuration: await (async () => {
1071
- const statDateKey = formatDate(todayStart, effectiveTimezone);
1072
- const todayStat = await models.taskDailyStatistics.findOne({
1073
- where: { date: statDateKey },
1074
- raw: true
1075
- });
1076
-
1077
- const emptyDuration = () => ({
1078
- completedCount: 0,
1079
- successCount: 0,
1080
- failedCount: 0,
1081
- canceledCount: 0,
1082
- avgWaitingTime: 0,
1083
- avgExecutionTime: 0,
1084
- avgTotalTime: 0,
1085
- byType: {},
1086
- byRunnerType: {}
1087
- });
1088
-
1089
- const mapStatToDuration = baseStat => {
1090
- if (!baseStat) return emptyDuration();
1091
- const typeData = type && baseStat.byType && baseStat.byType[type] ? baseStat.byType[type] : null;
1092
- const runnerTypeData = runnerType && baseStat.byRunnerType && baseStat.byRunnerType[runnerType] ? baseStat.byRunnerType[runnerType] : null;
1093
- const filterData = runnerTypeData || typeData;
1094
- const mainTimedTaskCount = filterData ? filterData.timedTaskCount : baseStat.timedTaskCount;
1095
- const mainTotalWaitingTime = filterData ? filterData.totalWaitingTime : baseStat.totalWaitingTime;
1096
- const mainTotalExecutionTime = filterData ? filterData.totalExecutionTime : baseStat.totalExecutionTime;
1097
- const mainTotalTime = filterData ? filterData.totalTime : baseStat.totalTime;
1098
-
1099
- return {
1100
- completedCount: filterData ? filterData.count : baseStat.totalCompleted,
1101
- successCount: filterData ? filterData.successCount : baseStat.successCount,
1102
- failedCount: filterData ? filterData.failedCount : baseStat.failedCount,
1103
- canceledCount: filterData ? filterData.canceledCount : baseStat.canceledCount,
1104
- avgWaitingTime: mainTimedTaskCount > 0 ? Math.round(mainTotalWaitingTime / mainTimedTaskCount) : 0,
1105
- avgExecutionTime: mainTimedTaskCount > 0 ? Math.round(mainTotalExecutionTime / mainTimedTaskCount) : 0,
1106
- avgTotalTime: mainTimedTaskCount > 0 ? Math.round(mainTotalTime / mainTimedTaskCount) : 0,
1107
- byType: Object.entries(baseStat.byType || {}).reduce((acc, [key, val]) => {
1108
- if (type && key !== type) return acc;
1109
- acc[key] = {
1110
- count: val.count,
1111
- avgWaitingTime: val.timedTaskCount > 0 ? Math.round(val.totalWaitingTime / val.timedTaskCount) : 0,
1112
- avgExecutionTime: val.timedTaskCount > 0 ? Math.round(val.totalExecutionTime / val.timedTaskCount) : 0,
1113
- avgTotalTime: val.timedTaskCount > 0 ? Math.round(val.totalTime / val.timedTaskCount) : 0
1114
- };
1115
- return acc;
1116
- }, {}),
1117
- byRunnerType: Object.entries(baseStat.byRunnerType || {}).reduce((acc, [key, val]) => {
1118
- if (runnerType && key !== runnerType) return acc;
1119
- acc[key] = {
1120
- count: val.count,
1121
- avgWaitingTime: val.timedTaskCount > 0 ? Math.round(val.totalWaitingTime / val.timedTaskCount) : 0,
1122
- avgExecutionTime: val.timedTaskCount > 0 ? Math.round(val.totalExecutionTime / val.timedTaskCount) : 0,
1123
- avgTotalTime: val.timedTaskCount > 0 ? Math.round(val.totalTime / val.timedTaskCount) : 0
1124
- };
1125
- return acc;
1126
- }, {})
1127
- };
1128
- };
1129
-
1130
- const aggregateDurationFromTodayTasks = async () => {
1131
- const terminalStatuses = ['success', 'failed', 'canceled'];
1132
- const tasks = await taskModel.findAll({
1133
- where: {
1134
- ...whereToday,
1135
- status: { [Op.in]: terminalStatuses },
1136
- completedAt: { [Op.ne]: null }
1137
- },
1138
- attributes: ['type', 'runnerType', 'status', 'createdAt', 'startedAt', 'completedAt'],
1139
- raw: true
1140
- });
1141
-
1142
- const newBucket = () => ({
1143
- count: 0,
1144
- successCount: 0,
1145
- failedCount: 0,
1146
- canceledCount: 0,
1147
- totalWaitingTime: 0,
1148
- totalExecutionTime: 0,
1149
- totalTime: 0,
1150
- timedTaskCount: 0
1151
- });
1152
-
1153
- const bump = (bucket, task, timing) => {
1154
- bucket.count += 1;
1155
- if (task.status === 'success') bucket.successCount += 1;
1156
- else if (task.status === 'failed') bucket.failedCount += 1;
1157
- else if (task.status === 'canceled') bucket.canceledCount += 1;
1158
- if (timing.hasTiming) {
1159
- bucket.totalWaitingTime += timing.waitingTime;
1160
- bucket.totalExecutionTime += timing.executionTime;
1161
- bucket.totalTime += timing.totalTime;
1162
- bucket.timedTaskCount += 1;
1163
- }
1164
- };
1165
-
1166
- const byTypeAcc = {};
1167
- const byRunnerAcc = {};
1168
- const main = newBucket();
1169
-
1170
- for (const task of tasks) {
1171
- const timing = computeTaskTiming(task);
1172
- bump(main, task, timing);
1173
- if (!byTypeAcc[task.type]) byTypeAcc[task.type] = newBucket();
1174
- bump(byTypeAcc[task.type], task, timing);
1175
- const rt = task.runnerType || 'system';
1176
- if (!byRunnerAcc[rt]) byRunnerAcc[rt] = newBucket();
1177
- bump(byRunnerAcc[rt], task, timing);
1178
- }
1179
-
1180
- const finalizeBuckets = acc =>
1181
- Object.entries(acc).reduce((out, [key, b]) => {
1182
- out[key] = {
1183
- count: b.count,
1184
- avgWaitingTime: b.timedTaskCount > 0 ? Math.round(b.totalWaitingTime / b.timedTaskCount) : 0,
1185
- avgExecutionTime: b.timedTaskCount > 0 ? Math.round(b.totalExecutionTime / b.timedTaskCount) : 0,
1186
- avgTotalTime: b.timedTaskCount > 0 ? Math.round(b.totalTime / b.timedTaskCount) : 0
1187
- };
1188
- return out;
1189
- }, {});
1190
-
1191
- return {
1192
- completedCount: main.count,
1193
- successCount: main.successCount,
1194
- failedCount: main.failedCount,
1195
- canceledCount: main.canceledCount,
1196
- avgWaitingTime: main.timedTaskCount > 0 ? Math.round(main.totalWaitingTime / main.timedTaskCount) : 0,
1197
- avgExecutionTime: main.timedTaskCount > 0 ? Math.round(main.totalExecutionTime / main.timedTaskCount) : 0,
1198
- avgTotalTime: main.timedTaskCount > 0 ? Math.round(main.totalTime / main.timedTaskCount) : 0,
1199
- byType: finalizeBuckets(byTypeAcc),
1200
- byRunnerType: finalizeBuckets(byRunnerAcc)
1201
- };
1202
- };
1203
-
1204
- const fromTasks = await aggregateDurationFromTodayTasks();
1205
-
1206
- const statHasAggregate = ts =>
1207
- ts &&
1208
- (Number(ts.totalCompleted) > 0 ||
1209
- Number(ts.timedTaskCount) > 0 ||
1210
- (ts.byType && Object.keys(ts.byType).length > 0) ||
1211
- (ts.byRunnerType && Object.keys(ts.byRunnerType).length > 0));
1212
-
1213
- if (todayStat && statHasAggregate(todayStat)) {
1214
- return mapStatToDuration(todayStat);
1215
- }
1216
- if (fromTasks.completedCount > 0) {
1217
- return fromTasks;
1218
- }
1219
- if (todayStat) {
1220
- return mapStatToDuration(todayStat);
1221
- }
1222
- return emptyDuration();
1223
- })()
1224
- };
1225
- }
1226
- };
1227
-
1228
547
  Object.assign(fastify[options.name].services, {
1229
548
  create,
1230
549
  detail,
@@ -1241,7 +560,6 @@ module.exports = fp(async (fastify, options) => {
1241
560
  executor,
1242
561
  processNext,
1243
562
  processSystemTask,
1244
- waitingComplete,
1245
- statistics
563
+ waitingComplete
1246
564
  });
1247
565
  });