forked from grafana/k6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummary.js
414 lines (369 loc) · 10.8 KB
/
summary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
var forEach = function (obj, callback) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(key, obj[key])) {
break
}
}
}
}
var palette = {
bold: 1,
faint: 2,
red: 31,
green: 32,
cyan: 36,
//TODO: add others?
}
var groupPrefix = '█'
var detailsPrefix = '↳'
var succMark = '✓'
var failMark = '✗'
var defaultOptions = {
indent: ' ',
enableColors: true,
summaryTimeUnit: null,
summaryTrendStats: null,
}
// strWidth tries to return the actual width the string will take up on the
// screen, without any terminal formatting, unicode ligatures, etc.
function strWidth(s) {
// TODO: determine if NFC or NFKD are not more appropriate? or just give up? https://hsivonen.fi/string-length/
var data = s.normalize('NFKC') // This used to be NFKD in Go, but this should be better
var inEscSeq = false
var inLongEscSeq = false
var width = 0
for (var char of data) {
if (char.done) {
break
}
// Skip over ANSI escape codes.
if (char == '\x1b') {
inEscSeq = true
continue
}
if (inEscSeq && char == '[') {
inLongEscSeq = true
continue
}
if (inEscSeq && inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x7e) {
inEscSeq = false
inLongEscSeq = false
continue
}
if (inEscSeq && !inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x5f) {
inEscSeq = false
continue
}
if (!inEscSeq && !inLongEscSeq) {
width++
}
}
return width
}
function summarizeCheck(indent, check, decorate) {
if (check.fails == 0) {
return decorate(indent + succMark + ' ' + check.name, palette.green)
}
var succPercent = Math.floor((100 * check.passes) / (check.passes + check.fails))
return decorate(
indent +
failMark +
' ' +
check.name +
'\n' +
indent +
' ' +
detailsPrefix +
' ' +
succPercent +
'% — ' +
succMark +
' ' +
check.passes +
' / ' +
failMark +
' ' +
check.fails,
palette.red
)
}
function summarizeGroup(indent, group, decorate) {
var result = []
if (group.name != '') {
result.push(indent + groupPrefix + ' ' + group.name + '\n')
indent = indent + ' '
}
for (var i = 0; i < group.checks.length; i++) {
result.push(summarizeCheck(indent, group.checks[i], decorate))
}
if (group.checks.length > 0) {
result.push('')
}
for (var i = 0; i < group.groups.length; i++) {
Array.prototype.push.apply(result, summarizeGroup(indent, group.groups[i], decorate))
}
return result
}
function displayNameForMetric(name) {
var subMetricPos = name.indexOf('{')
if (subMetricPos >= 0) {
return '{ ' + name.substring(subMetricPos + 1, name.length - 1) + ' }'
}
return name
}
function indentForMetric(name) {
if (name.indexOf('{') >= 0) {
return ' '
}
return ''
}
function humanizeBytes(bytes) {
var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
var base = 1000
if (bytes < 10) {
return bytes + ' B'
}
var e = Math.floor(Math.log(bytes) / Math.log(base))
var suffix = units[e | 0]
var val = Math.floor((bytes / Math.pow(base, e)) * 10 + 0.5) / 10
return val.toFixed(val < 10 ? 1 : 0) + ' ' + suffix
}
var unitMap = {
s: { unit: 's', coef: 0.001 },
ms: { unit: 'ms', coef: 1 },
us: { unit: 'µs', coef: 1000 },
}
function toFixedNoTrailingZeros(val, prec) {
// TODO: figure out something better?
return parseFloat(val.toFixed(prec)).toString()
}
function toFixedNoTrailingZerosTrunc(val, prec) {
var mult = Math.pow(10, prec)
return toFixedNoTrailingZeros(Math.trunc(mult * val) / mult, prec)
}
function humanizeGenericDuration(dur) {
if (dur === 0) {
return '0s'
}
if (dur < 0.001) {
// smaller than a microsecond, print nanoseconds
return Math.trunc(dur * 1000000) + 'ns'
}
if (dur < 1) {
// smaller than a millisecond, print microseconds
return toFixedNoTrailingZerosTrunc(dur * 1000, 2) + 'µs'
}
if (dur < 1000) {
// duration is smaller than a second
return toFixedNoTrailingZerosTrunc(dur, 2) + 'ms'
}
var result = toFixedNoTrailingZerosTrunc((dur % 60000) / 1000, dur > 60000 ? 0 : 2) + 's'
var rem = Math.trunc(dur / 60000)
if (rem < 1) {
// less than a minute
return result
}
result = (rem % 60) + 'm' + result
rem = Math.trunc(rem / 60)
if (rem < 1) {
// less than an hour
return result
}
return rem + 'h' + result
}
function humanizeDuration(dur, timeUnit) {
if (timeUnit !== '' && unitMap.hasOwnProperty(timeUnit)) {
return (dur * unitMap[timeUnit].coef).toFixed(2) + unitMap[timeUnit].unit
}
return humanizeGenericDuration(dur)
}
function humanizeValue(val, metric, timeUnit) {
if (metric.type == 'rate') {
// Truncate instead of round when decreasing precision to 2 decimal places
return (Math.trunc(val * 100 * 100) / 100).toFixed(2) + '%'
}
switch (metric.contains) {
case 'data':
return humanizeBytes(val)
case 'time':
return humanizeDuration(val, timeUnit)
default:
return toFixedNoTrailingZeros(val, 6)
}
}
function nonTrendMetricValueForSum(metric, timeUnit) {
switch (metric.type) {
case 'counter':
return [
humanizeValue(metric.values.count, metric, timeUnit),
humanizeValue(metric.values.rate, metric, timeUnit) + '/s',
]
case 'gauge':
return [
humanizeValue(metric.values.value, metric, timeUnit),
'min=' + humanizeValue(metric.values.min, metric, timeUnit),
'max=' + humanizeValue(metric.values.max, metric, timeUnit),
]
case 'rate':
return [
humanizeValue(metric.values.rate, metric, timeUnit),
succMark + ' ' + metric.values.passes,
failMark + ' ' + metric.values.fails,
]
default:
return ['[no data]']
}
}
function summarizeMetrics(options, data, decorate) {
var indent = options.indent + ' '
var result = []
var names = []
var nameLenMax = 0
var nonTrendValues = {}
var nonTrendValueMaxLen = 0
var nonTrendExtras = {}
var nonTrendExtraMaxLens = [0, 0]
var trendCols = {}
var numTrendColumns = options.summaryTrendStats.length
var trendColMaxLens = new Array(numTrendColumns).fill(0)
forEach(data.metrics, function (name, metric) {
names.push(name)
// When calculating widths for metrics, account for the indentation on submetrics.
var displayName = indentForMetric(name) + displayNameForMetric(name)
var displayNameWidth = strWidth(displayName)
if (displayNameWidth > nameLenMax) {
nameLenMax = displayNameWidth
}
if (metric.type == 'trend') {
var cols = []
for (var i = 0; i < numTrendColumns; i++) {
var tc = options.summaryTrendStats[i]
var value = metric.values[tc]
if (tc === 'count') {
value = value.toString()
} else {
value = humanizeValue(value, metric, options.summaryTimeUnit)
}
var valLen = strWidth(value)
if (valLen > trendColMaxLens[i]) {
trendColMaxLens[i] = valLen
}
cols[i] = value
}
trendCols[name] = cols
return
}
var values = nonTrendMetricValueForSum(metric, options.summaryTimeUnit)
nonTrendValues[name] = values[0]
var valueLen = strWidth(values[0])
if (valueLen > nonTrendValueMaxLen) {
nonTrendValueMaxLen = valueLen
}
nonTrendExtras[name] = values.slice(1)
for (var i = 1; i < values.length; i++) {
var extraLen = strWidth(values[i])
if (extraLen > nonTrendExtraMaxLens[i - 1]) {
nonTrendExtraMaxLens[i - 1] = extraLen
}
}
})
// sort all metrics but keep sub metrics grouped with their parent metrics
names.sort(function (metric1, metric2) {
var parent1 = metric1.split('{', 1)[0]
var parent2 = metric2.split('{', 1)[0]
var result = parent1.localeCompare(parent2)
if (result !== 0) {
return result
}
var sub1 = metric1.substring(parent1.length)
var sub2 = metric2.substring(parent2.length)
return sub1.localeCompare(sub2)
})
var getData = function (name) {
if (trendCols.hasOwnProperty(name)) {
var cols = trendCols[name]
var tmpCols = new Array(numTrendColumns)
for (var i = 0; i < cols.length; i++) {
tmpCols[i] =
options.summaryTrendStats[i] +
'=' +
decorate(cols[i], palette.cyan) +
' '.repeat(trendColMaxLens[i] - strWidth(cols[i]))
}
return tmpCols.join(' ')
}
var value = nonTrendValues[name]
var fmtData = decorate(value, palette.cyan) + ' '.repeat(nonTrendValueMaxLen - strWidth(value))
var extras = nonTrendExtras[name]
if (extras.length == 1) {
fmtData = fmtData + ' ' + decorate(extras[0], palette.cyan, palette.faint)
} else if (extras.length > 1) {
var parts = new Array(extras.length)
for (var i = 0; i < extras.length; i++) {
parts[i] =
decorate(extras[i], palette.cyan, palette.faint) +
' '.repeat(nonTrendExtraMaxLens[i] - strWidth(extras[i]))
}
fmtData = fmtData + ' ' + parts.join(' ')
}
return fmtData
}
for (var name of names) {
var metric = data.metrics[name]
var mark = ' '
var markColor = function (text) {
return text
} // noop
if (metric.thresholds) {
mark = succMark
markColor = function (text) {
return decorate(text, palette.green)
}
forEach(metric.thresholds, function (name, threshold) {
if (!threshold.ok) {
mark = failMark
markColor = function (text) {
return decorate(text, palette.red)
}
return true // break
}
})
}
var fmtIndent = indentForMetric(name)
var fmtName = displayNameForMetric(name)
fmtName =
fmtName +
decorate(
'.'.repeat(nameLenMax - strWidth(fmtName) - strWidth(fmtIndent) + 3) + ':',
palette.faint
)
result.push(indent + fmtIndent + markColor(mark) + ' ' + fmtName + ' ' + getData(name))
}
return result
}
function generateTextSummary(data, options) {
var mergedOpts = Object.assign({}, defaultOptions, data.options, options)
var lines = []
// TODO: move all of these functions into an object with methods?
var decorate = function (text) {
return text
}
if (mergedOpts.enableColors) {
decorate = function (text, color /*, ...rest*/) {
var result = '\x1b[' + color
for (var i = 2; i < arguments.length; i++) {
result += ';' + arguments[i]
}
return result + 'm' + text + '\x1b[0m'
}
}
Array.prototype.push.apply(
lines,
summarizeGroup(mergedOpts.indent + ' ', data.root_group, decorate)
)
Array.prototype.push.apply(lines, summarizeMetrics(mergedOpts, data, decorate))
return lines.join('\n')
}
exports.humanizeValue = humanizeValue
exports.textSummary = generateTextSummary