@kne/fastify-task 3.0.0-alpha.3 → 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.
- package/README.md +548 -274
- package/libs/controllers/main.js +4 -0
- package/libs/controllers/statistics.js +5 -2
- package/libs/models/task.js +5 -0
- package/libs/services/main.js +67 -13
- package/libs/services/statistics.js +473 -339
- package/package.json +2 -2
|
@@ -1,10 +1,4 @@
|
|
|
1
1
|
const fp = require('fastify-plugin');
|
|
2
|
-
const dayjs = require('dayjs');
|
|
3
|
-
const utc = require('dayjs/plugin/utc');
|
|
4
|
-
const timezone = require('dayjs/plugin/timezone');
|
|
5
|
-
|
|
6
|
-
dayjs.extend(utc);
|
|
7
|
-
dayjs.extend(timezone);
|
|
8
2
|
|
|
9
3
|
const RANGE_MAP = {
|
|
10
4
|
'7d': { value: 7, unit: 'day', label: '近7天' },
|
|
@@ -13,6 +7,9 @@ const RANGE_MAP = {
|
|
|
13
7
|
'1y': { value: 1, unit: 'year', label: '近1年' }
|
|
14
8
|
};
|
|
15
9
|
|
|
10
|
+
const RUNNER_TYPES = ['system', 'manual'];
|
|
11
|
+
const STAT_ATTRS = ['total', 'success', 'failed', 'canceled', 'waitingTime', 'executionTime', 'totalTime'];
|
|
12
|
+
|
|
16
13
|
const parseRange = (range = '7d') => {
|
|
17
14
|
const config = RANGE_MAP[range];
|
|
18
15
|
if (!config) {
|
|
@@ -20,398 +17,535 @@ const parseRange = (range = '7d') => {
|
|
|
20
17
|
}
|
|
21
18
|
const now = new Date();
|
|
22
19
|
const startTime = new Date(now);
|
|
23
|
-
if (config.unit === 'day')
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
startTime.setMonth(startTime.getMonth() - config.value);
|
|
27
|
-
} else if (config.unit === 'year') {
|
|
28
|
-
startTime.setFullYear(startTime.getFullYear() - config.value);
|
|
29
|
-
}
|
|
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);
|
|
30
23
|
return { startTime, endTime: now, label: config.label, range };
|
|
31
24
|
};
|
|
32
25
|
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
/** 解析通道: type:runnerType:hour */
|
|
38
|
-
const parseChannel = channel => {
|
|
39
|
-
const parts = channel.split(':');
|
|
40
|
-
return {
|
|
41
|
-
type: parts[0] || null,
|
|
42
|
-
runnerType: parts[1] || null,
|
|
43
|
-
hour: parts[2] !== undefined ? parseInt(parts[2], 10) : null
|
|
44
|
-
};
|
|
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')}`;
|
|
45
29
|
};
|
|
46
30
|
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
runner: (types, rts = RUNNER_TYPES) => types.flatMap(t => rts.map(rt => `${t}:${rt}`)),
|
|
51
|
-
hour: (types, rts = RUNNER_TYPES) => types.flatMap(t =>
|
|
52
|
-
rts.flatMap(rt => Array.from({ length: 24 }, (_, h) => `${t}:${rt}:${h}`))
|
|
53
|
-
)
|
|
31
|
+
const safeNum = v => {
|
|
32
|
+
const n = Number(v);
|
|
33
|
+
return (typeof n === 'number' && !isNaN(n) ? n : 0);
|
|
54
34
|
};
|
|
55
35
|
|
|
56
|
-
|
|
57
|
-
const filterByPeriod = (list, period) => (list || []).filter(item => item.period === period);
|
|
36
|
+
const getSumData = item => (item.data || {}).sum || item.data || {};
|
|
58
37
|
|
|
59
|
-
|
|
60
|
-
const getSumData = item => {
|
|
61
|
-
const data = item.data || {};
|
|
62
|
-
return data.sum || data;
|
|
63
|
-
};
|
|
38
|
+
const computeAvg = (sum, count) => (count > 0 ? Math.round(sum / count) : 0);
|
|
64
39
|
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
waitingQueueMaxWaitMsByRunnerType: {}, completedTodayTotalDurationMsByRunnerType: {}
|
|
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)
|
|
72
46
|
});
|
|
73
47
|
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
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
|
+
};
|
|
79
54
|
|
|
80
|
-
|
|
81
|
-
const
|
|
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
|
+
};
|
|
82
68
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
+
};
|
|
88
74
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const todayDate = now.format('YYYY-MM-DD');
|
|
97
|
-
|
|
98
|
-
const taskTypes = await getTaskTypes();
|
|
99
|
-
if (taskTypes.length === 0) return emptyRealtimeResult(todayDate);
|
|
100
|
-
|
|
101
|
-
const typeChannels = buildChannels.type(taskTypes);
|
|
102
|
-
const runnerChannels = buildChannels.runner(taskTypes);
|
|
103
|
-
const hourChannels = buildChannels.hour(taskTypes);
|
|
104
|
-
|
|
105
|
-
// 1. 按类型查询计数汇总
|
|
106
|
-
const typeCountResult = await statisticsServices.query({
|
|
107
|
-
channels: typeChannels, startTime: todayStart, endTime: now.toDate(),
|
|
108
|
-
attributeNames: COUNT_ATTRIBUTES, aggregates: ['sum'], timezone: tz
|
|
109
|
-
});
|
|
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
|
+
};
|
|
110
82
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
channels: runnerChannels, startTime: todayStart, endTime: now.toDate(),
|
|
114
|
-
attributeNames: COUNT_ATTRIBUTES, aggregates: ['sum'], timezone: tz
|
|
115
|
-
});
|
|
83
|
+
// 创建空的 dailyMap 条目
|
|
84
|
+
const createDailyMapEntry = () => ({ total: 0, byStatus: { success: 0, failed: 0, canceled: 0 }, byType: {} });
|
|
116
85
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
+
});
|
|
122
92
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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;
|
|
136
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;
|
|
137
191
|
}
|
|
138
192
|
}
|
|
139
193
|
|
|
140
|
-
//
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
+
}
|
|
160
214
|
}
|
|
161
|
-
if (sumData.pending !== undefined) pendingByRunnerType[runnerType] = Math.round(sumData.pending);
|
|
162
|
-
if (sumData.success !== undefined) completedToday[runnerType] = Math.round(sumData.success);
|
|
163
|
-
}
|
|
164
215
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const sumData = getSumData(item);
|
|
173
|
-
const count = sumData.total !== undefined ? Math.round(sumData.total) : 0;
|
|
174
|
-
|
|
175
|
-
if (!hourBuckets[localHour]) hourBuckets[localHour] = { total: 0, byType: {}, byStatus: {} };
|
|
176
|
-
const bucket = hourBuckets[localHour];
|
|
177
|
-
bucket.total += count;
|
|
178
|
-
if (taskType) bucket.byType[taskType] = (bucket.byType[taskType] || 0) + count;
|
|
179
|
-
for (const status of COUNT_ATTRIBUTES) {
|
|
180
|
-
if (status !== 'total' && sumData[status] !== undefined) {
|
|
181
|
-
bucket.byStatus[status] = (bucket.byStatus[status] || 0) + Math.round(sumData[status]);
|
|
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 };
|
|
182
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);
|
|
183
229
|
}
|
|
184
230
|
}
|
|
231
|
+
}
|
|
185
232
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
+
}));
|
|
193
248
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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 });
|
|
207
303
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
avgWaitingTime: Math.round(totalAvgWait / durationCount),
|
|
212
|
-
avgTotalTime: Math.round(totalAvgTotal / durationCount)
|
|
213
|
-
} : null;
|
|
214
|
-
|
|
215
|
-
// 等待队列最长等待时间(max 聚合)
|
|
216
|
-
const maxWaitResult = await statisticsServices.query({
|
|
217
|
-
channels: runnerChannels, startTime: todayStart, endTime: now.toDate(),
|
|
218
|
-
attributeNames: ['waitingTime'], aggregates: ['max'], timezone: tz
|
|
219
|
-
});
|
|
220
|
-
const waitingQueueMaxWaitMsByRunnerType = {};
|
|
221
|
-
for (const item of maxWaitResult.list || []) {
|
|
222
|
-
const { runnerType } = parseChannel(item.channel);
|
|
223
|
-
if (!runnerType) continue;
|
|
224
|
-
const maxData = item.data?.max || item.data || {};
|
|
225
|
-
if (maxData.waitingTime !== undefined) {
|
|
226
|
-
const v = Math.round(maxData.waitingTime);
|
|
227
|
-
if (!waitingQueueMaxWaitMsByRunnerType[runnerType] || v > waitingQueueMaxWaitMsByRunnerType[runnerType]) {
|
|
228
|
-
waitingQueueMaxWaitMsByRunnerType[runnerType] = v;
|
|
229
|
-
}
|
|
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 });
|
|
230
307
|
}
|
|
231
308
|
}
|
|
232
309
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
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
|
+
}
|
|
246
324
|
}
|
|
247
325
|
}
|
|
326
|
+
}
|
|
248
327
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
hourlyTrend, hourlyTrendByType, hourlyTrendByStatus, todayDuration,
|
|
252
|
-
waitingByRunnerType, pendingByRunnerType, completedToday, runnerTypeStats,
|
|
253
|
-
waitingQueueMaxWaitMsByRunnerType, completedTodayTotalDurationMsByRunnerType
|
|
254
|
-
};
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* 历史统计:通过统计模块查询
|
|
259
|
-
*/
|
|
260
|
-
const queryHistoryData = async ({ range = '7d', timezone, type, runnerType }) => {
|
|
261
|
-
const { startTime, endTime } = parseRange(range);
|
|
262
|
-
const tz = timezone || undefined;
|
|
263
|
-
|
|
264
|
-
const taskTypes = type ? [type] : await getTaskTypes();
|
|
265
|
-
const runnerTypes = runnerType ? [runnerType] : RUNNER_TYPES;
|
|
266
|
-
|
|
267
|
-
if (taskTypes.length === 0) return emptyHistoryResult();
|
|
268
|
-
|
|
269
|
-
const typeChannels = buildChannels.type(taskTypes);
|
|
270
|
-
const runnerChannels = buildChannels.runner(taskTypes, runnerTypes);
|
|
271
|
-
const hourChannels = buildChannels.hour(taskTypes, runnerTypes);
|
|
328
|
+
return { hourlyTrend, hourlyTrendByStatus, hourlyTrendByType, hourlyCompletionTrend };
|
|
329
|
+
};
|
|
272
330
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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 };
|
|
342
|
+
};
|
|
278
343
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
});
|
|
344
|
+
module.exports = fp(async (fastify, options) => {
|
|
345
|
+
const statisticsServices = fastify[`${options.name}Statistics`].services;
|
|
346
|
+
const { task: TaskModel } = fastify[options.name].models;
|
|
347
|
+
const { Op, fn, col } = fastify.sequelize.Sequelize;
|
|
284
348
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
}
|
|
349
|
+
// ─── queryStatistics (history 接口) ───
|
|
350
|
+
const queryStatistics = async ({ range = '7d', timezone, type, runnerType }) => {
|
|
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;
|
|
300
379
|
}
|
|
380
|
+
};
|
|
301
381
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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
|
+
]);
|
|
315
402
|
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
403
|
+
const pendingByRunnerType = {};
|
|
404
|
+
const waitingByRunnerType = {};
|
|
405
|
+
const runningByRunnerType = {};
|
|
319
406
|
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
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;
|
|
324
414
|
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
if (
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
if (
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
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;
|
|
347
436
|
}
|
|
348
|
-
if (
|
|
349
|
-
|
|
437
|
+
if (r.status === 'waiting') {
|
|
438
|
+
runnerTypeStats[r.runnerType].waiting += count;
|
|
439
|
+
runnerTypeStats[r.runnerType].waitingCount += count;
|
|
350
440
|
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
const hourlyCompletionTrend = Object.values(hourDayMap).map(b => ({
|
|
354
|
-
date: b.date, hour: b.hour, totalCompleted: b.total,
|
|
355
|
-
...b.byStatus,
|
|
356
|
-
...Object.fromEntries(Object.entries(b.byType).map(([t, c]) => [`${t}Count`, c]))
|
|
357
|
-
}));
|
|
358
|
-
|
|
359
|
-
// 时长趋势(按日 + runnerType 聚合平均执行/等待时长)
|
|
360
|
-
const durationResult = await statisticsServices.query({
|
|
361
|
-
channels: runnerChannels, startTime, endTime,
|
|
362
|
-
attributeNames: TIMING_ATTRIBUTES, aggregates: ['avg', 'sum', 'count'], timezone: tz
|
|
363
441
|
});
|
|
364
442
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
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
|
+
};
|
|
385
462
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
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
|
+
}
|
|
389
497
|
}
|
|
498
|
+
} catch (e) {
|
|
499
|
+
fastify.log.error(`SSE统计查询失败: ${e.message}`);
|
|
390
500
|
}
|
|
391
501
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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 });
|
|
395
508
|
|
|
396
509
|
return {
|
|
397
|
-
|
|
398
|
-
|
|
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
|
|
399
527
|
};
|
|
400
528
|
};
|
|
401
529
|
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
return await queryHistoryData({ range, timezone, type, runnerType });
|
|
405
|
-
};
|
|
406
|
-
|
|
407
|
-
/** SSE 接口:实时统计推送 */
|
|
408
|
-
const sseStatistics = async ({ timezone, interval }, reply) => {
|
|
530
|
+
// ─── sseStatistics ───
|
|
531
|
+
const sseStatistics = async ({ range = '7d', timezone, type, runnerType, interval }, reply) => {
|
|
409
532
|
await statisticsServices.sseStream.send(reply, {
|
|
410
|
-
name: '
|
|
411
|
-
|
|
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
|
+
}
|
|
542
|
+
},
|
|
412
543
|
interval: interval || 5
|
|
413
544
|
});
|
|
414
545
|
};
|
|
415
546
|
|
|
416
|
-
Object.assign(fastify[options.name].services, {
|
|
547
|
+
Object.assign(fastify[options.name].services, {
|
|
548
|
+
queryStatistics,
|
|
549
|
+
sseStatistics
|
|
550
|
+
});
|
|
417
551
|
});
|