-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLogs.js
293 lines (263 loc) · 7.91 KB
/
Logs.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
import React, {
useCallback,
useState,
useRef,
useEffect,
useMemo,
} from "react";
import { RobotManager, Features } from "@mov-ai/mov-fe-lib-core";
import useSub from "../../hooks/useSub";
import RobotLogModal from "../Modal/RobotLogModal";
import LogsFilterBar from "./LogsFilterBar/LogsFilterBar";
import LogsTable from "./LogsTable/LogsTable";
import { ROBOT_LOG_TYPE } from "./utils/Constants";
import { COLUMNS_LABEL } from "./utils/Constants";
import useUpdateEffect from "./hooks/useUpdateEffect";
import _isEqual from "lodash/isEqual";
import { useStyles } from "./styles";
import { logsSub } from "./sub";
import "./Logs.css";
/**
* Tranform log from the format received from the API to the format
* required to be rendered
* @returns {array} Transformed log
*/
function transformLog(log, _index, _data, ts_multiplier = 1000) {
const timestamp = ts_multiplier * log.time;
const date = new Date(timestamp);
return {
...log,
timestamp,
time: date.toLocaleTimeString(),
date: date.toLocaleDateString(),
key: log.message + timestamp,
};
}
/**
* Remove duplicates from logs for the second overlaping the
* current and the last request
* @returns {array} Concatenated logs without duplicates
*/
export function logsDedupe(oldLogs, data) {
if (!data.length) return oldLogs;
// date of the oldest log received in the current request
const oldDate = data[data.length - 1].timestamp;
// map to store the old logs of the overlaped second
let map = {};
// iter over old logs with last timestamp of the new logs
// and put in a map
for (let i = 0; i < oldLogs.length && oldLogs[i].timestamp === oldDate; i++)
map[oldLogs[i].message] = oldLogs[i];
// array to store logs from overlap second which had not
// been sent before
let newSecOverlap = [];
let z;
// iter over new logs (oldest to latest) with last timestamp,
// check if present in last map
// - if not, push
for (z = data.length - 1; z >= 0 && data[z].timestamp === oldDate; z--)
if (!map[data[z].message]) newSecOverlap.push(data[z]);
// cut new logs up to z, concat with the deduped ones
// and the old logs up to i
return data.slice(0, z + 1).concat(newSecOverlap.reverse(), oldLogs);
}
// TODO this should be exported. Fleetboard uses it
function blobDownload(file, fileName, charset = "text/plain;charset=utf-8") {
const blob = new Blob([file], { type: charset });
const url = URL.createObjectURL(blob);
const a = globalThis.document.createElement("a");
globalThis.document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
globalThis.document.body.removeChild(a);
}
function noSelection(obj) {
for (let key in obj) {
if (obj[key]) return false;
}
return true;
}
function getRobots(robotsData) {
return robotsData
.map((robot) => robot.name)
.reduce((a, robot) => ({ ...a, [robot]: true }), {});
}
function matchTags(tags, item) {
for (const tag in tags)
if (item[tag] !== undefined) continue;
else return false;
return true;
}
const MAX_FETCH_LOGS = 20000;
const MAX_LOGS = 2000;
let logsDataGlobal = [];
const Logs = (props) => {
const { robotsData, hide, force, defaults } = props;
const classes = useStyles();
const getLogsTimeoutRef = useRef();
const refreshLogsTimeoutRef = useRef();
const handleContainerRef = useRef();
const logModalRef = useRef();
const sub = useSub(logsSub);
const {
robots,
levels,
service,
columns,
tags,
message,
selectedFromDate,
selectedToDate,
} = sub;
const [logsData, setLogsData] = useState(logsDataGlobal);
const restLogs = useMemo(() => !Features.get("logStreaming"), []);
const filteredLogs = useMemo(
() =>
logsDataGlobal
.filter(
(item) =>
(levels[item.level] || noSelection(levels)) &&
(service[item.service] || noSelection(service)) &&
(matchTags(tags, item) || noSelection(tags)) &&
(item.message || "").includes(message) &&
(robots[item.robot] || noSelection(robots)) &&
(!selectedFromDate || item.timestamp >= selectedFromDate) &&
(!selectedToDate || item.timestamp <= selectedToDate),
)
.slice(0, MAX_LOGS),
[
logsData,
levels,
service,
message,
tags,
robots,
selectedFromDate,
selectedToDate,
],
);
useEffect(() => {
for (const key of Object.keys(props.force ?? {}))
logsSub.set(key, {
...sub[key],
...force[key].reduce((a, subKey) => ({ ...a, [subKey]: "force" }), {}),
});
}, [force]);
useEffect(() => {
for (const key of Object.keys(props.defaults ?? {}))
logsSub.set(key, {
...sub[key],
...defaults[key],
});
}, [defaults]);
// if robotsData changes, update robots
useEffect(() => {
logsSub.set("robots", getRobots(robotsData));
}, [robotsData]);
const getLogs = useCallback(() => {
// Remove previously enqueued requests
clearTimeout(getLogsTimeoutRef.current);
RobotManager.getLogs({
limit: MAX_FETCH_LOGS,
date: {
from: logsDataGlobal.length
? logsDataGlobal[0].timestamp
: selectedFromDate,
to: selectedToDate,
},
}).then((response) => {
const data = response?.data || [];
const oldLogs = logsDataGlobal || [];
const newLogs = (logsDataGlobal = logsDedupe(
oldLogs,
data.map(transformLog),
).slice(0, MAX_FETCH_LOGS));
setLogsData(newLogs);
});
}, [
selectedFromDate,
selectedToDate,
logsData,
setLogsData,
robotsData,
restLogs,
]);
const sock = useMemo(() => (restLogs ? null : RobotManager.openLogs({})), []);
useEffect(() => {
getLogs();
}, []);
const onMessage = useCallback(
(msg) => {
const item = JSON.parse(msg?.data ?? {});
setLogsData(
(prevState) =>
(logsDataGlobal = [
transformLog(item, 0, [item], 0.000001),
...prevState,
].slice(0, MAX_FETCH_LOGS)),
);
},
[setLogsData],
);
useEffect(() => {
if (restLogs) return;
sock.onmessage = onMessage;
return () => {
sock.close();
};
}, [onMessage, sock, restLogs]);
useUpdateEffect(() => {
if (restLogs) {
clearTimeout(refreshLogsTimeoutRef.current);
refreshLogsTimeoutRef.current = setTimeout(() => {
getLogs();
}, 1000);
}
}, [getLogs, restLogs]);
const handleExport = useCallback(() => {
const sep = "\t";
const contents = filteredLogs.map((log) => {
const { date, time, robot, message } = log;
return [date, time, robot, message].join(sep);
});
// from https://www.epochconverter.com/programming/
const dateString = !filteredLogs.length
? new Date().toISOString()
: new Date(filteredLogs[0].timestamp * 0.001).toISOString();
const columnLabels = Object.keys(columns)
.filter((key) => columns[key])
.map((key) => COLUMNS_LABEL[key]);
blobDownload(
[columnLabels.join(sep), ...contents].join("\n"),
`movai-logs-${dateString}.csv`,
"text/csv;charset=utf-8",
);
}, [columns, filteredLogs]);
const openLogDetails = useCallback((log) => {
logModalRef.current.open(log.rowData);
}, []);
return (
<div className={classes.externalDiv}>
<div data-testid="section_logs" className={classes.wrapper}>
<LogsFilterBar handleExport={handleExport} hide={hide} />
<div
data-testid="section_table-container"
ref={handleContainerRef}
className={classes.tableContainer}
>
<LogsTable
columns={columns}
logsData={filteredLogs}
levels={levels}
onRowClick={openLogDetails}
></LogsTable>
</div>
</div>
<RobotLogModal ref={logModalRef} props={ROBOT_LOG_TYPE}></RobotLogModal>
</div>
);
};
export default Logs;