-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
89 lines (74 loc) · 2.04 KB
/
app.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
import { Transform } from 'stream';
import readline from 'readline';
import saveData from './db.js';
const logToObject = (logLine) => logLine.split(' | ').reduce((parsed, pairWord) => {
const [key, value] = pairWord.split(': ');
if (key && value) return { ...parsed, [key]: value };
return parsed;
}, {});
const calculateStats = (tags, parsed, init = {}) => {
if (!parsed.duration) return init;
const duration = parseFloat(parsed.duration);
const operationType = parsed.operationType.toLowerCase();
return tags.reduce((processed, tagName) => {
const tagValue = parsed[tagName];
if (!tagValue) return processed;
const record = processed[tagName]?.[tagValue] || { count: 0, totalDuration: 0 };
const count = record.count + 1;
const totalDuration = record.totalDuration + duration;
const averageDuration = totalDuration / count;
return {
...processed,
[tagName]: {
...processed[tagName],
[tagValue]: {
count, totalDuration, averageDuration, operationType,
},
},
};
}, init);
};
class StatsAggregator extends Transform {
constructor() {
super({ defaultEncoding: 'utf8' });
this.output = {};
}
_transform(chunk, _, next) {
this.output = calculateStats(
['operation', 'operationType'],
logToObject(chunk.toString()),
this.output,
);
next();
}
_flush() {
console.log('operation types:');
console.table(this.output.operationType, [
'count',
'averageDuration',
'maxDuration',
'minDuration',
]);
console.log('operations:');
console.table(this.output.operation, [
'count',
'averageDuration',
'maxDuration',
'minDuration',
'operationType',
]);
saveData(this.output.operation);
}
}
const statsAggregator = new StatsAggregator();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
rl.on('line', (line) => {
statsAggregator.write(line);
});
rl.on('close', () => {
statsAggregator.end();
});