forked from y-scope/yscope-log-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
387 lines (347 loc) · 12.4 KB
/
index.ts
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
/* eslint max-lines: ["error", 400] */
import {
Decoder,
DecoderOptionsType,
} from "../../typings/decoders";
import {MAX_V8_STRING_LENGTH} from "../../typings/js";
import {LogLevelFilter} from "../../typings/logs";
import {
BeginLineNumToLogEventNumMap,
CURSOR_CODE,
CursorData,
CursorType,
EMPTY_PAGE_RESP,
FileSrcType,
QueryResults,
WORKER_RESP_CODE,
WorkerResp,
} from "../../typings/worker";
import {
EXPORT_LOGS_CHUNK_SIZE,
SEARCH_CHUNK_SIZE,
} from "../../utils/config";
import {getChunkNum} from "../../utils/math";
import {defer} from "../../utils/time";
import {formatSizeInBytes} from "../../utils/units";
import ClpIrDecoder from "../decoders/ClpIrDecoder";
import JsonlDecoder from "../decoders/JsonlDecoder";
import {
getEventNumCursorData,
getLastEventCursorData,
getPageNumCursorData,
loadFile,
} from "./utils";
/**
* Class to manage the retrieval and decoding of a given log file.
*/
class LogFileManager {
readonly #fileName: string;
readonly #numEvents: number = 0;
readonly #pageSize: number;
#queryId: number = 0;
readonly #onDiskFileSizeInBytes: number;
readonly #onQueryResults: (queryResults: QueryResults) => void;
#decoder: Decoder;
/**
* Private constructor for LogFileManager. This is not intended to be invoked publicly.
* Instead, use LogFileManager.create() to create a new instance of the class.
*
* @param params
* @param params.decoder
* @param params.fileName
* @param params.onDiskFileSizeInBytes
* @param params.pageSize Page size for setting up pagination.
* @param params.onQueryResults The callback function to handle query results.
*/
constructor ({decoder, fileName, onDiskFileSizeInBytes, pageSize, onQueryResults}: {
decoder: Decoder,
fileName: string,
onDiskFileSizeInBytes: number,
pageSize: number,
onQueryResults: (queryResults: QueryResults) => void,
}) {
this.#decoder = decoder;
this.#fileName = fileName;
this.#pageSize = pageSize;
this.#onDiskFileSizeInBytes = onDiskFileSizeInBytes;
this.#onQueryResults = onQueryResults;
// Build index for the entire file.
const buildResult = decoder.build();
if (0 < buildResult.numInvalidEvents) {
console.error("Invalid events found in decoder.build():", buildResult);
}
this.#numEvents = decoder.getEstimatedNumEvents();
console.log(`Found ${this.#numEvents} log events.`);
}
get fileName () {
return this.#fileName;
}
get onDiskFileSizeInBytes () {
return this.#onDiskFileSizeInBytes;
}
get numEvents () {
return this.#numEvents;
}
/**
* Creates a new LogFileManager.
*
* @param fileSrc The source of the file to load. This can be a string representing a URL, or a
* File object.
* @param pageSize Page size for setting up pagination.
* @param decoderOptions Initial decoder options.
* @param onQueryResults
* @return A Promise that resolves to the created LogFileManager instance.
*/
static async create (
fileSrc: FileSrcType,
pageSize: number,
decoderOptions: DecoderOptionsType,
onQueryResults: (queryResults: QueryResults) => void,
): Promise<LogFileManager> {
const {fileName, fileData} = await loadFile(fileSrc);
const decoder = await LogFileManager.#initDecoder(fileName, fileData, decoderOptions);
return new LogFileManager({
decoder: decoder,
fileName: fileName,
onDiskFileSizeInBytes: fileData.length,
pageSize: pageSize,
onQueryResults: onQueryResults,
});
}
/**
* Constructs a decoder instance based on the file extension.
*
* @param fileName
* @param fileData
* @param decoderOptions Initial decoder options.
* @return The constructed decoder.
* @throws {Error} if no decoder supports a file with the given extension.
*/
static async #initDecoder (
fileName: string,
fileData: Uint8Array,
decoderOptions: DecoderOptionsType
): Promise<Decoder> {
let decoder: Decoder;
if (fileName.endsWith(".jsonl")) {
decoder = new JsonlDecoder(fileData, decoderOptions);
} else if (fileName.endsWith(".clp.zst")) {
decoder = await ClpIrDecoder.create(fileData);
} else {
throw new Error(`No decoder supports ${fileName}`);
}
if (fileData.length > MAX_V8_STRING_LENGTH) {
throw new Error(`Cannot handle files larger than ${
formatSizeInBytes(MAX_V8_STRING_LENGTH)
} due to a limitation in Chromium-based browsers.`);
}
return decoder;
}
/* Sets any formatter options that exist in the decoder's options.
* @param options
*/
setFormatterOptions (options: DecoderOptionsType) {
this.#decoder.setFormatterOptions(options);
}
/**
* Sets the log level filter.
*
* @param logLevelFilter
* @throws {Error} If the log level filter couldn't be set.
*/
setLogLevelFilter (logLevelFilter: LogLevelFilter) {
const result = this.#decoder.setLogLevelFilter(logLevelFilter);
if (false === result) {
throw new Error("Failed to set log level filter for the decoder.");
}
}
/**
* Loads log events in the range
* [`beginLogEventIdx`, `beginLogEventIdx + EXPORT_LOGS_CHUNK_SIZE`), or all remaining log
* events if `EXPORT_LOGS_CHUNK_SIZE` log events aren't available.
*
* @param beginLogEventIdx
* @return An object containing the log events as a string.
* @throws {Error} if any error occurs when decoding the log events.
*/
loadChunk (beginLogEventIdx: number): {
logs: string,
} {
const endLogEventIdx = Math.min(beginLogEventIdx + EXPORT_LOGS_CHUNK_SIZE, this.#numEvents);
const results = this.#decoder.decodeRange(
beginLogEventIdx,
endLogEventIdx,
false,
);
if (null === results) {
throw new Error(
`Failed to decode log events in range [${beginLogEventIdx}, ${endLogEventIdx})`
);
}
const messages = results.map(([msg]) => msg);
return {
logs: messages.join(""),
};
}
/**
* Loads a page of log events based on the provided cursor.
*
* @param cursor The cursor indicating the page to load. See {@link CursorType}.
* @return An object containing the logs as a string, a map of line numbers to log event
* numbers, and the line number of the first line in the cursor identified event.
* @throws {Error} if any error occurs during decode.
*/
loadPage (cursor: CursorType): WorkerResp<WORKER_RESP_CODE.PAGE_DATA> {
console.debug(`loadPage: cursor=${JSON.stringify(cursor)}`);
const filteredLogEventMap = this.#decoder.getFilteredLogEventMap();
const numActiveEvents: number = filteredLogEventMap ?
filteredLogEventMap.length :
this.#numEvents;
if (0 === numActiveEvents) {
return EMPTY_PAGE_RESP;
}
const {
pageBegin,
pageEnd,
matchingEvent,
} = this.#getCursorData(cursor, numActiveEvents);
const results = this.#decoder.decodeRange(
pageBegin,
pageEnd,
null !== filteredLogEventMap,
);
if (null === results) {
throw new Error("Error occurred during decoding. " +
`pageBegin=${pageBegin}, ` +
`pageEnd=${pageEnd}`);
}
const messages: string[] = [];
const beginLineNumToLogEventNum: BeginLineNumToLogEventNumMap = new Map();
let currentLine = 1;
results.forEach((r) => {
const [
msg,
,
,
logEventNum,
] = r;
messages.push(msg);
beginLineNumToLogEventNum.set(currentLine, logEventNum);
currentLine += msg.split("\n").length - 1;
});
const newNumPages: number = getChunkNum(numActiveEvents, this.#pageSize);
const newPageNum: number = getChunkNum(pageBegin + 1, this.#pageSize);
const matchingLogEventNum = 1 + (
null !== filteredLogEventMap ?
(filteredLogEventMap[matchingEvent] as number) :
matchingEvent
);
return {
beginLineNumToLogEventNum: beginLineNumToLogEventNum,
cursorLineNum: 1,
logEventNum: matchingLogEventNum,
logs: messages.join(""),
numPages: newNumPages,
pageNum: newPageNum,
};
}
/**
* Searches for log events based on the given search string.
*
* @param searchString
* @param isRegex
* @param isCaseSensitive
*/
startQuery (searchString: string, isRegex: boolean, isCaseSensitive: boolean): void {
// If the search string is empty, or there are no logs, return
if ("" === searchString || 0 === this.#numEvents) {
return;
}
// Construct search RegExp
const regexPattern = isRegex ?
searchString :
searchString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regexFlags = isCaseSensitive ?
"" :
"i";
const searchRegex = new RegExp(regexPattern, regexFlags);
this.#searchChunkAndScheduleNext(this.#queryId++, 0, searchRegex);
}
/**
* Searches for log events in the given range, then schedules itself to search the next chunk.
*
* @param queryId
* @param beginSearchIdx The beginning index of the search range.
* @param searchRegex The regular expression to search.
*/
#searchChunkAndScheduleNext (
queryId: number,
beginSearchIdx: number,
searchRegex: RegExp
): void {
if (queryId !== this.#queryId) {
// Current task no longer corresponds to the latest query in the LogFileManager.
return;
}
const endSearchIdx = Math.min(beginSearchIdx + SEARCH_CHUNK_SIZE, this.#numEvents);
const results: QueryResults = new Map();
const decodedEvents = this.#decoder.decodeRange(
beginSearchIdx,
endSearchIdx,
null !== this.#decoder.getFilteredLogEventMap()
);
decodedEvents?.forEach(([message, , , logEventNum]) => {
const match = message.match(searchRegex);
if (match && "number" === typeof match.index) {
const pageNum = Math.ceil(logEventNum / this.#pageSize);
if (false === results.has(pageNum)) {
results.set(pageNum, []);
}
results.get(pageNum)?.push({
logEventNum: logEventNum,
message: message,
matchRange: [match.index,
(match.index + match[0].length)],
});
}
});
this.#onQueryResults(results);
if (endSearchIdx < this.#numEvents) {
defer(() => {
this.#searchChunkAndScheduleNext(queryId, endSearchIdx, searchRegex);
});
}
}
/**
* Gets the data that corresponds to the cursor.
*
* @param cursor
* @param numActiveEvents
* @return Cursor data.
* @throws {Error} if the type of cursor is not supported.
*/
#getCursorData (cursor: CursorType, numActiveEvents: number): CursorData {
const {code, args} = cursor;
switch (code) {
case CURSOR_CODE.PAGE_NUM:
return getPageNumCursorData(
args.pageNum,
args.eventPositionOnPage,
numActiveEvents,
this.#pageSize,
);
case CURSOR_CODE.LAST_EVENT:
return getLastEventCursorData(numActiveEvents, this.#pageSize);
case CURSOR_CODE.EVENT_NUM:
return getEventNumCursorData(
args.eventNum,
numActiveEvents,
this.#pageSize,
this.#decoder.getFilteredLogEventMap(),
);
default:
throw new Error(`Unsupported cursor type: ${code}`);
}
}
}
export default LogFileManager;