@kne/fastify-task 3.0.0-alpha.2 → 3.0.0-alpha.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.
@@ -7,6 +7,9 @@ const RANGE_MAP = {
7
7
  '1y': { value: 1, unit: 'year', label: '近1年' }
8
8
  };
9
9
 
10
+ const RUNNER_TYPES = ['system', 'manual'];
11
+ const STAT_ATTRS = ['total', 'success', 'failed', 'canceled', 'waitingTime', 'executionTime', 'totalTime'];
12
+
10
13
  const parseRange = (range = '7d') => {
11
14
  const config = RANGE_MAP[range];
12
15
  if (!config) {
@@ -14,55 +17,528 @@ const parseRange = (range = '7d') => {
14
17
  }
15
18
  const now = new Date();
16
19
  const startTime = new Date(now);
17
- if (config.unit === 'day') {
18
- startTime.setDate(startTime.getDate() - config.value);
19
- } else if (config.unit === 'month') {
20
- startTime.setMonth(startTime.getMonth() - config.value);
21
- } else if (config.unit === 'year') {
22
- startTime.setFullYear(startTime.getFullYear() - config.value);
23
- }
20
+ if (config.unit === 'day') startTime.setDate(startTime.getDate() - config.value);
21
+ else if (config.unit === 'month') startTime.setMonth(startTime.getMonth() - config.value);
22
+ else if (config.unit === 'year') startTime.setFullYear(startTime.getFullYear() - config.value);
24
23
  return { startTime, endTime: now, label: config.label, range };
25
24
  };
26
25
 
27
- const buildChannel = ({ type, runnerType }) => {
28
- if (type && runnerType) return `task:${type}:${runnerType}`;
29
- if (type) return `task:${type}`;
30
- return 'task';
26
+ const formatDate = date => {
27
+ const d = new Date(date);
28
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
29
+ };
30
+
31
+ const safeNum = v => {
32
+ const n = Number(v);
33
+ return (typeof n === 'number' && !isNaN(n) ? n : 0);
34
+ };
35
+
36
+ const getSumData = item => (item.data || {}).sum || item.data || {};
37
+
38
+ const computeAvg = (sum, count) => (count > 0 ? Math.round(sum / count) : 0);
39
+
40
+ // 将原始时长累加器 {count, sum*} 转为输出格式 {count, avg*}
41
+ const toAvgDuration = ({ count, sumWaiting, sumExecution, sumTotal }) => ({
42
+ count,
43
+ avgWaitingTime: computeAvg(sumWaiting, count),
44
+ avgExecutionTime: computeAvg(sumExecution, count),
45
+ avgTotalTime: computeAvg(sumTotal, count)
46
+ });
47
+
48
+ const parseChannel = channel => {
49
+ const parts = channel.split(':');
50
+ return parts.length >= 2
51
+ ? { type: parts[0], runnerType: parts[1] }
52
+ : { type: channel, runnerType: null };
53
+ };
54
+
55
+ const buildChannels = async (statisticsServices, type, runnerType) => {
56
+ const metaResult = await statisticsServices.channelMeta.list();
57
+ const list = Array.isArray(metaResult) ? metaResult : metaResult.list || [];
58
+ const rootChannels = list.map(meta => meta.channel).filter(Boolean);
59
+ const types = type ? rootChannels.filter(ch => ch === type) : rootChannels;
60
+ const rts = runnerType ? [runnerType] : RUNNER_TYPES;
61
+ const channels = [];
62
+ for (const t of types) {
63
+ channels.push(t);
64
+ for (const rt of rts) channels.push(`${t}:${rt}`);
65
+ }
66
+ return channels;
67
+ };
68
+
69
+ // 确保时长累加器存在于 map 中
70
+ const ensureDurationAcc = (map, key) => {
71
+ if (!map[key]) map[key] = { count: 0, sumWaiting: 0, sumExecution: 0, sumTotal: 0 };
72
+ return map[key];
73
+ };
74
+
75
+ // 累加时长到累加器
76
+ const accumDuration = (acc, count, sum) => {
77
+ acc.count += count;
78
+ acc.sumWaiting += safeNum(sum.waitingTime);
79
+ acc.sumExecution += safeNum(sum.executionTime);
80
+ acc.sumTotal += safeNum(sum.totalTime);
81
+ };
82
+
83
+ // 创建空的 dailyMap 条目
84
+ const createDailyMapEntry = () => ({ total: 0, byStatus: { success: 0, failed: 0, canceled: 0 }, byType: {} });
85
+
86
+ // 创建空的 dailyDurationMap 条目
87
+ const createDailyDurationEntry = () => ({
88
+ completedCount: 0, successCount: 0, failedCount: 0, canceledCount: 0,
89
+ sumWaiting: 0, sumExecution: 0, sumTotal: 0, countWithTiming: 0,
90
+ byType: {}, byRunnerType: {}
91
+ });
92
+
93
+ // 查询 statistics 并解析结果
94
+ const queryAndParse = async (statisticsServices, { channels, startTime, endTime, timezone, runnerType: runnerTypeFilter }) => {
95
+ if (channels.length === 0) return null;
96
+
97
+ const statResult = await statisticsServices.query({
98
+ channels, startTime, endTime,
99
+ attributeNames: STAT_ATTRS,
100
+ aggregates: ['sum'],
101
+ timezone: timezone || undefined
102
+ });
103
+
104
+ const result = {
105
+ totalTasks: 0,
106
+ byStatus: { success: 0, failed: 0, canceled: 0 },
107
+ byType: {},
108
+ byRunnerType: {},
109
+ dailyMap: {},
110
+ hourlyMap: {},
111
+ hourlyStatusMap: {},
112
+ hourlyTypeMap: {},
113
+ hourlyDetailMap: {},
114
+ duration: {
115
+ completedCount: 0, successCount: 0, failedCount: 0, canceledCount: 0,
116
+ sumWaiting: 0, sumExecution: 0, sumTotal: 0, countWithTiming: 0,
117
+ byType: {}, byRunnerType: {}, byTypeByRunnerType: {}
118
+ },
119
+ durationTrend: []
120
+ };
121
+ const dailyDurationMap = {};
122
+
123
+ for (const item of statResult.list || []) {
124
+ const { type: typeName, runnerType: runnerTypeName } = parseChannel(item.channel);
125
+ if (runnerTypeFilter && runnerTypeName && runnerTypeName !== runnerTypeFilter) continue;
126
+ if (runnerTypeFilter && !runnerTypeName) continue;
127
+
128
+ const sum = getSumData(item);
129
+ const count = safeNum(sum.total);
130
+ const isHourly = item.period === 'h';
131
+ const date = formatDate(item.time);
132
+ const hour = isHourly ? new Date(item.time).getHours() : null;
133
+
134
+ // ─── 1-segment channel: 全局 + 按日 + 时长 聚合 ───
135
+ if (!runnerTypeName) {
136
+ // 全局汇总
137
+ result.totalTasks += count;
138
+ result.byStatus.success += safeNum(sum.success);
139
+ result.byStatus.failed += safeNum(sum.failed);
140
+ result.byStatus.canceled += safeNum(sum.canceled);
141
+ result.byType[typeName] = (result.byType[typeName] || 0) + count;
142
+
143
+ // 全局时长
144
+ result.duration.completedCount += count;
145
+ result.duration.successCount += safeNum(sum.success);
146
+ result.duration.failedCount += safeNum(sum.failed);
147
+ result.duration.canceledCount += safeNum(sum.canceled);
148
+ result.duration.sumWaiting += safeNum(sum.waitingTime);
149
+ result.duration.sumExecution += safeNum(sum.executionTime);
150
+ result.duration.sumTotal += safeNum(sum.totalTime);
151
+ result.duration.countWithTiming += count;
152
+ if (count > 0) accumDuration(ensureDurationAcc(result.duration.byType, typeName), count, sum);
153
+
154
+ // 按日汇总
155
+ if (!result.dailyMap[date]) result.dailyMap[date] = createDailyMapEntry();
156
+ const dm = result.dailyMap[date];
157
+ dm.total += count;
158
+ dm.byStatus.success += safeNum(sum.success);
159
+ dm.byStatus.failed += safeNum(sum.failed);
160
+ dm.byStatus.canceled += safeNum(sum.canceled);
161
+ dm.byType[typeName] = (dm.byType[typeName] || 0) + count;
162
+
163
+ // 按日时长
164
+ if (!dailyDurationMap[date]) dailyDurationMap[date] = createDailyDurationEntry();
165
+ const dd = dailyDurationMap[date];
166
+ dd.completedCount += count;
167
+ dd.successCount += safeNum(sum.success);
168
+ dd.failedCount += safeNum(sum.failed);
169
+ dd.canceledCount += safeNum(sum.canceled);
170
+ dd.sumWaiting += safeNum(sum.waitingTime);
171
+ dd.sumExecution += safeNum(sum.executionTime);
172
+ dd.sumTotal += safeNum(sum.totalTime);
173
+ dd.countWithTiming += count;
174
+ if (count > 0) accumDuration(ensureDurationAcc(dd.byType, typeName), count, sum);
175
+
176
+ // 小时级趋势(仅 period='h')
177
+ if (isHourly) {
178
+ if (!result.hourlyMap[date]) result.hourlyMap[date] = {};
179
+ result.hourlyMap[date][hour] = (result.hourlyMap[date][hour] || 0) + count;
180
+
181
+ if (!result.hourlyStatusMap[date]) result.hourlyStatusMap[date] = {};
182
+ if (!result.hourlyStatusMap[date][hour]) result.hourlyStatusMap[date][hour] = {};
183
+ for (const status of ['success', 'failed', 'canceled']) {
184
+ const sc = safeNum(sum[status]);
185
+ if (sc > 0) result.hourlyStatusMap[date][hour][status] = (result.hourlyStatusMap[date][hour][status] || 0) + sc;
186
+ }
187
+
188
+ if (!result.hourlyTypeMap[date]) result.hourlyTypeMap[date] = {};
189
+ if (!result.hourlyTypeMap[date][hour]) result.hourlyTypeMap[date][hour] = {};
190
+ if (count > 0) result.hourlyTypeMap[date][hour][typeName] = (result.hourlyTypeMap[date][hour][typeName] || 0) + count;
191
+ }
192
+ }
193
+
194
+ // ─── 2-segment channel: byRunnerType 聚合 ───
195
+ if (runnerTypeName) {
196
+ result.byRunnerType[runnerTypeName] = (result.byRunnerType[runnerTypeName] || 0) + count;
197
+
198
+ if (count > 0) {
199
+ accumDuration(ensureDurationAcc(result.duration.byRunnerType, runnerTypeName), count, sum);
200
+
201
+ // byTypeByRunnerType(覆盖写入,非累加)
202
+ if (!result.duration.byTypeByRunnerType[runnerTypeName]) result.duration.byTypeByRunnerType[runnerTypeName] = {};
203
+ result.duration.byTypeByRunnerType[runnerTypeName][typeName] = {
204
+ count,
205
+ sumWaiting: safeNum(sum.waitingTime),
206
+ sumExecution: safeNum(sum.executionTime),
207
+ sumTotal: safeNum(sum.totalTime)
208
+ };
209
+
210
+ // 按日 byRunnerType 时长
211
+ if (dailyDurationMap[date]) {
212
+ accumDuration(ensureDurationAcc(dailyDurationMap[date].byRunnerType, runnerTypeName), count, sum);
213
+ }
214
+ }
215
+
216
+ // hourlyDetailMap(仅 period='h')
217
+ if (isHourly) {
218
+ if (!result.hourlyDetailMap[date]) result.hourlyDetailMap[date] = {};
219
+ if (!result.hourlyDetailMap[date][hour]) result.hourlyDetailMap[date][hour] = {};
220
+ if (!result.hourlyDetailMap[date][hour][typeName]) result.hourlyDetailMap[date][hour][typeName] = {};
221
+ if (!result.hourlyDetailMap[date][hour][typeName][runnerTypeName]) {
222
+ result.hourlyDetailMap[date][hour][typeName][runnerTypeName] = { total: 0, success: 0, failed: 0, canceled: 0 };
223
+ }
224
+ const detail = result.hourlyDetailMap[date][hour][typeName][runnerTypeName];
225
+ detail.total += count;
226
+ detail.success += safeNum(sum.success);
227
+ detail.failed += safeNum(sum.failed);
228
+ detail.canceled += safeNum(sum.canceled);
229
+ }
230
+ }
231
+ }
232
+
233
+ // 构建按日时长趋势
234
+ result.durationTrend = Object.entries(dailyDurationMap)
235
+ .sort(([a], [b]) => a.localeCompare(b))
236
+ .map(([date, dd]) => ({
237
+ date,
238
+ completedCount: dd.completedCount,
239
+ successCount: dd.successCount,
240
+ failedCount: dd.failedCount,
241
+ canceledCount: dd.canceledCount,
242
+ avgWaitingTime: computeAvg(dd.sumWaiting, dd.countWithTiming),
243
+ avgExecutionTime: computeAvg(dd.sumExecution, dd.countWithTiming),
244
+ avgTotalTime: computeAvg(dd.sumTotal, dd.countWithTiming),
245
+ byType: Object.fromEntries(Object.entries(dd.byType).map(([n, td]) => [n, toAvgDuration(td)])),
246
+ byRunnerType: Object.fromEntries(Object.entries(dd.byRunnerType).map(([n, rt]) => [n, toAvgDuration(rt)]))
247
+ }));
248
+
249
+ return result;
250
+ };
251
+
252
+ // 构建 todayDuration 结果
253
+ const buildDurationResult = (d) => ({
254
+ completedCount: d.completedCount,
255
+ successCount: d.successCount,
256
+ failedCount: d.failedCount,
257
+ canceledCount: d.canceledCount,
258
+ avgWaitingTime: computeAvg(d.sumWaiting, d.countWithTiming),
259
+ avgExecutionTime: computeAvg(d.sumExecution, d.countWithTiming),
260
+ avgTotalTime: computeAvg(d.sumTotal, d.countWithTiming),
261
+ byType: Object.fromEntries(Object.entries(d.byType).map(([n, td]) => [n, toAvgDuration(td)])),
262
+ byRunnerType: Object.fromEntries(Object.entries(d.byRunnerType).map(([n, rt]) => [n, toAvgDuration(rt)])),
263
+ byTypeByRunnerType: Object.fromEntries(
264
+ Object.entries(d.byTypeByRunnerType).map(([rtName, types]) => [
265
+ rtName,
266
+ Object.fromEntries(Object.entries(types).map(([typeName, td]) => [typeName, toAvgDuration(td)]))
267
+ ])
268
+ )
269
+ });
270
+
271
+ // 构建小时趋势数组(完整格式,供 history 接口使用)
272
+ const buildHourlyTrendArrays = (parsed) => {
273
+ const hourlyTrend = [];
274
+ const hourlyTrendByStatus = [];
275
+ const hourlyTrendByType = [];
276
+ const hourlyCompletionTrend = [];
277
+
278
+ const dates = Object.keys(parsed.hourlyMap).sort();
279
+ for (const date of dates) {
280
+ const hoursMap = parsed.hourlyMap[date] || {};
281
+ const statusMap = parsed.hourlyStatusMap[date] || {};
282
+ const typeMap = parsed.hourlyTypeMap[date] || {};
283
+ const detailMap = parsed.hourlyDetailMap[date] || {};
284
+
285
+ const allHours = [...new Set([
286
+ ...Object.keys(hoursMap).map(Number),
287
+ ...Object.keys(statusMap).map(Number),
288
+ ...Object.keys(typeMap).map(Number),
289
+ ...Object.keys(detailMap).map(Number)
290
+ ])].sort((a, b) => a - b);
291
+
292
+ for (const hour of allHours) {
293
+ const statuses = statusMap[hour] || {};
294
+ hourlyTrend.push({
295
+ date, hour,
296
+ total: hoursMap[hour] || 0,
297
+ success: statuses.success || 0,
298
+ failed: statuses.failed || 0,
299
+ canceled: statuses.canceled || 0
300
+ });
301
+ for (const [status, count] of Object.entries(statuses)) {
302
+ if (count > 0) hourlyTrendByStatus.push({ date, hour, status, count });
303
+ }
304
+ const types = typeMap[hour] || {};
305
+ for (const [typeName, count] of Object.entries(types)) {
306
+ if (count > 0) hourlyTrendByType.push({ date, hour, type: typeName, count });
307
+ }
308
+ }
309
+
310
+ for (const hour of Object.keys(detailMap).map(Number).sort((a, b) => a - b)) {
311
+ const types = detailMap[hour] || {};
312
+ for (const [typeName, runnerTypes] of Object.entries(types)) {
313
+ for (const [runnerTypeName, detail] of Object.entries(runnerTypes)) {
314
+ if (detail.total > 0) {
315
+ hourlyCompletionTrend.push({
316
+ date, hour, type: typeName, runnerType: runnerTypeName,
317
+ totalCompleted: detail.total,
318
+ successCount: detail.success,
319
+ failedCount: detail.failed,
320
+ canceledCount: detail.canceled
321
+ });
322
+ }
323
+ }
324
+ }
325
+ }
326
+ }
327
+
328
+ return { hourlyTrend, hourlyTrendByStatus, hourlyTrendByType, hourlyCompletionTrend };
329
+ };
330
+
331
+ // 构建历史日趋势数组
332
+ const buildDailyTrendArrays = (parsed) => {
333
+ const sorted = Object.entries(parsed.dailyMap).sort(([a], [b]) => a.localeCompare(b));
334
+ const recentTrend = sorted.map(([date, d]) => ({ date, count: d.total }));
335
+ const recentTrendByStatus = [];
336
+ const recentTrendByType = [];
337
+ sorted.forEach(([date, d]) => {
338
+ Object.entries(d.byStatus).forEach(([status, count]) => recentTrendByStatus.push({ date, status, count }));
339
+ Object.entries(d.byType).forEach(([type, count]) => recentTrendByType.push({ date, type, count }));
340
+ });
341
+ return { recentTrend, recentTrendByStatus, recentTrendByType };
31
342
  };
32
343
 
33
344
  module.exports = fp(async (fastify, options) => {
34
345
  const statisticsServices = fastify[`${options.name}Statistics`].services;
346
+ const { task: TaskModel } = fastify[options.name].models;
347
+ const { Op, fn, col } = fastify.sequelize.Sequelize;
35
348
 
349
+ // ─── queryStatistics (history 接口) ───
36
350
  const queryStatistics = async ({ range = '7d', timezone, type, runnerType }) => {
37
- const { startTime, endTime } = parseRange(range);
38
- const channel = buildChannel({ type, runnerType });
39
- const includeChildren = !type && !runnerType;
40
-
41
- return await statisticsServices.query({
42
- channels: [channel],
43
- startTime,
44
- endTime,
45
- timezone: timezone || undefined,
46
- includeChildren
351
+ const { startTime, endTime, label, range: rangeKey } = parseRange(range);
352
+ const emptyResult = {
353
+ range: rangeKey, rangeLabel: label,
354
+ totalTasks: 0, byStatus: {}, byType: {}, byRunnerType: {},
355
+ recentTrend: [], recentTrendByStatus: [], recentTrendByType: [],
356
+ durationTrend: [], hourlyCompletionTrend: []
357
+ };
358
+ try {
359
+ const channels = await buildChannels(statisticsServices, type, runnerType);
360
+ const parsed = await queryAndParse(statisticsServices, { channels, startTime, endTime, timezone, runnerType });
361
+ if (!parsed) return emptyResult;
362
+
363
+ const { recentTrend, recentTrendByStatus, recentTrendByType } = buildDailyTrendArrays(parsed);
364
+ const { hourlyTrend, hourlyCompletionTrend } = buildHourlyTrendArrays(parsed);
365
+
366
+ return {
367
+ range: rangeKey, rangeLabel: label,
368
+ totalTasks: parsed.totalTasks,
369
+ byStatus: parsed.byStatus,
370
+ byType: parsed.byType,
371
+ byRunnerType: parsed.byRunnerType,
372
+ recentTrend, recentTrendByStatus, recentTrendByType,
373
+ durationTrend: parsed.durationTrend,
374
+ hourlyTrend, hourlyCompletionTrend
375
+ };
376
+ } catch (e) {
377
+ fastify.log.error(`查询统计数据失败: ${e.message}`);
378
+ return emptyResult;
379
+ }
380
+ };
381
+
382
+ // ─── buildSseData (SSE 接口) ───
383
+ const buildSseData = async ({ timezone, type, runnerType }) => {
384
+ const now = new Date();
385
+ const todayStart = new Date(now); todayStart.setHours(0, 0, 0, 0);
386
+ const todayEnd = new Date(now); todayEnd.setHours(23, 59, 59, 999);
387
+ const todayStr = formatDate(now);
388
+
389
+ // 统计查询:正在执行和等待执行的数量 + DB 查询
390
+ const [runnerTypeStatusRows, waitingTasks] = await Promise.all([
391
+ TaskModel.findAll({
392
+ attributes: ['runnerType', 'status', [fn('COUNT', col('id')), 'count']],
393
+ where: { ...(runnerType ? { runnerType } : {}) },
394
+ group: ['runnerType', 'status'], raw: true
395
+ }),
396
+ TaskModel.findAll({
397
+ attributes: ['runnerType', 'createdAt'],
398
+ where: { status: { [Op.in]: ['pending', 'waiting'] }, ...(runnerType ? { runnerType } : {}) },
399
+ raw: true
400
+ })
401
+ ]);
402
+
403
+ const pendingByRunnerType = {};
404
+ const waitingByRunnerType = {};
405
+ const runningByRunnerType = {};
406
+
407
+ const nowMs = Date.now();
408
+ const waitingQueueMaxWaitMsByRunnerType = {};
409
+ waitingTasks.forEach(r => {
410
+ const rt = r.runnerType || 'manual';
411
+ const waitMs = nowMs - new Date(r.createdAt).getTime();
412
+ if (!waitingQueueMaxWaitMsByRunnerType[rt] || waitMs > waitingQueueMaxWaitMsByRunnerType[rt]) {
413
+ waitingQueueMaxWaitMsByRunnerType[rt] = waitMs;
414
+ }
415
+ });
416
+
417
+ const runnerTypeStats = {};
418
+ const dbStatusCount = { pending: 0, waiting: 0, running: 0, success: 0, failed: 0, canceled: 0 };
419
+ runnerTypeStatusRows.forEach(r => {
420
+ if (!runnerTypeStats[r.runnerType]) runnerTypeStats[r.runnerType] = { total: 0, pending: 0, waiting: 0, waitingCount: 0, executed: 0 };
421
+ const count = Number(r.count);
422
+ const rt = r.runnerType || 'manual';
423
+ runnerTypeStats[r.runnerType].total += count;
424
+ if (r.status === 'pending') runnerTypeStats[r.runnerType].pending += count;
425
+ if (['success', 'failed', 'canceled', 'running'].includes(r.status)) runnerTypeStats[r.runnerType].executed += count;
426
+ if (dbStatusCount[r.status] !== undefined) dbStatusCount[r.status] += count;
427
+ // 按 runnerType 汇总 running/waiting/pending(来自 DB 实时状态,避免 delta 脏数据)
428
+ if (r.status === 'running') runningByRunnerType[rt] = (runningByRunnerType[rt] || 0) + count;
429
+ if (r.status === 'waiting') waitingByRunnerType[rt] = (waitingByRunnerType[rt] || 0) + count;
430
+ if (r.status === 'pending') pendingByRunnerType[rt] = (pendingByRunnerType[rt] || 0) + count;
431
+ // pending 状态等同于"等待操作",计入 waitingByRunnerType 和 runnerTypeStats.waiting/waitingCount
432
+ if (r.status === 'pending') {
433
+ waitingByRunnerType[rt] = (waitingByRunnerType[rt] || 0) + count;
434
+ runnerTypeStats[r.runnerType].waiting += count;
435
+ runnerTypeStats[r.runnerType].waitingCount += count;
436
+ }
437
+ if (r.status === 'waiting') {
438
+ runnerTypeStats[r.runnerType].waiting += count;
439
+ runnerTypeStats[r.runnerType].waitingCount += count;
440
+ }
47
441
  });
442
+
443
+ // Statistics 查询:已完成数据
444
+ // 默认值:DB 实时数据(即使 statistics 服务不可用也能展示 running/waiting/pending)
445
+ // pending 全部合并到 waiting:前端"等待操作"只有 waiting 类别,不展示独立的 pending
446
+ const dbWaitingTotal = dbStatusCount.waiting + dbStatusCount.pending;
447
+ let totalTasks = dbStatusCount.running + dbWaitingTotal;
448
+ let byStatus = { success: 0, failed: 0, canceled: 0, running: dbStatusCount.running, waiting: dbWaitingTotal, pending: 0 };
449
+ let byType = {};
450
+ let byRunnerType = {};
451
+ let completedToday = {};
452
+ let completedTodayTotalDurationMsByRunnerType = {};
453
+ let hourlyTrend = [];
454
+ let hourlyTrendByStatus = [];
455
+ let hourlyTrendByType = [];
456
+ let intervalTrend = [];
457
+ let todayDuration = {
458
+ completedCount: 0, successCount: 0, failedCount: 0, canceledCount: 0,
459
+ avgWaitingTime: 0, avgExecutionTime: 0, avgTotalTime: 0,
460
+ byType: {}, byRunnerType: {}, byTypeByRunnerType: {}
461
+ };
462
+
463
+ try {
464
+ const channels = await buildChannels(statisticsServices, type, runnerType);
465
+ const parsed = await queryAndParse(statisticsServices, { channels, startTime: todayStart, endTime: todayEnd, timezone, runnerType });
466
+ if (parsed) {
467
+ totalTasks = parsed.totalTasks + dbStatusCount.running + dbWaitingTotal;
468
+ byStatus = { ...parsed.byStatus, running: dbStatusCount.running, waiting: dbWaitingTotal, pending: 0 };
469
+ byType = parsed.byType;
470
+ byRunnerType = parsed.byRunnerType;
471
+ completedToday = { ...parsed.byRunnerType };
472
+ todayDuration = buildDurationResult(parsed.duration);
473
+
474
+ const hourlyArrays = buildHourlyTrendArrays(parsed);
475
+
476
+ // SSE 格式:简化为 {hour, count},只取当天
477
+ hourlyTrend = hourlyArrays.hourlyTrend
478
+ .filter(h => h.date === todayStr)
479
+ .map(({ hour, total }) => ({ hour, count: total }));
480
+
481
+ hourlyTrendByStatus = hourlyArrays.hourlyTrendByStatus
482
+ .filter(h => h.date === todayStr)
483
+ .map(({ hour, status, count }) => ({ hour, status, count }));
484
+
485
+ hourlyTrendByType = hourlyArrays.hourlyTrendByType
486
+ .filter(h => h.date === todayStr)
487
+ .map(({ hour, type, count }) => ({ hour, type, count }));
488
+
489
+ intervalTrend = hourlyTrend.map(({ hour, count }) => ({
490
+ interval: `${String(hour).padStart(2, '0')}:00`,
491
+ count
492
+ }));
493
+
494
+ for (const [rtName, rt] of Object.entries(parsed.duration.byRunnerType)) {
495
+ completedTodayTotalDurationMsByRunnerType[rtName] = rt.sumTotal;
496
+ }
497
+ }
498
+ } catch (e) {
499
+ fastify.log.error(`SSE统计查询失败: ${e.message}`);
500
+ }
501
+
502
+ // 补充当前小时的 running/waiting 瞬时状态(来自 DB 实时查询,不受 statistics 服务影响)
503
+ // 放在 try/catch 之后,确保无论 parsed 是否存在都能追加 DB 实时数据
504
+ // pending 已合并到 waiting,前端不单独展示 pending
505
+ const currentHour = now.getHours();
506
+ if (dbStatusCount.running > 0) hourlyTrendByStatus.push({ hour: currentHour, status: 'running', count: dbStatusCount.running });
507
+ if (dbWaitingTotal > 0) hourlyTrendByStatus.push({ hour: currentHour, status: 'waiting', count: dbWaitingTotal });
508
+
509
+ return {
510
+ date: todayStr,
511
+ totalTasks,
512
+ byStatus,
513
+ byType,
514
+ byRunnerType,
515
+ pendingByRunnerType,
516
+ waitingByRunnerType,
517
+ runningByRunnerType,
518
+ completedToday,
519
+ waitingQueueMaxWaitMsByRunnerType,
520
+ completedTodayTotalDurationMsByRunnerType,
521
+ runnerTypeStats,
522
+ hourlyTrend,
523
+ hourlyTrendByStatus,
524
+ hourlyTrendByType,
525
+ intervalTrend,
526
+ todayDuration
527
+ };
48
528
  };
49
529
 
530
+ // ─── sseStatistics ───
50
531
  const sseStatistics = async ({ range = '7d', timezone, type, runnerType, interval }, reply) => {
51
- const channel = buildChannel({ type, runnerType });
52
- const includeChildren = !type && !runnerType;
53
-
54
532
  await statisticsServices.sseStream.send(reply, {
55
- name: 'query',
56
- params: { channels: channel, timezone, includeChildren },
57
- fetchData: async () => {
58
- const { startTime, endTime } = parseRange(range);
59
- return statisticsServices.query({
60
- channels: [channel],
61
- startTime,
62
- endTime,
63
- timezone: timezone || undefined,
64
- includeChildren
65
- });
533
+ name: 'taskStatistics',
534
+ params: { type, runnerType, timezone },
535
+ fetchData: async ({ type, runnerType, timezone } = {}) => {
536
+ try {
537
+ return await buildSseData({ timezone, type, runnerType });
538
+ } catch (e) {
539
+ fastify.log.error(`SSE获取数据失败: ${e.message}`);
540
+ return {};
541
+ }
66
542
  },
67
543
  interval: interval || 5
68
544
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-task",
3
- "version": "3.0.0-alpha.2",
3
+ "version": "3.0.0-alpha.4",
4
4
  "description": "一个 Fastify 插件,用于任务编排、追踪任务执行状态和结果。支持系统自动执行和手动执行两种模式,提供完整的任务生命周期管理",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -56,7 +56,7 @@
56
56
  "sqlite3": "^5.1.7"
57
57
  },
58
58
  "dependencies": {
59
- "@kne/fastify-statistics": "^0.1.0-alpha.5",
59
+ "@kne/fastify-statistics": "^0.1.0-alpha.10",
60
60
  "fastify-cron": "^1.4.0",
61
61
  "fs-extra": "^11.3.0"
62
62
  }