LiveLogService.uts
1.28 KB
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
import { Logger } from "@/services/logger/LoggerCore.uts";
export type LiveLogSender = (line: string) => Promise<void>;
export class LiveLogService {
private enabled: boolean = false;
private flushing: boolean = false;
private logger = Logger.getInstance();
private queue: string[] = [];
private sender: LiveLogSender | null = null;
constructor() {
this.logger.setLogListener((line: string): void => {
if (!this.enabled || this.sender == null) {
return;
}
this.queue.push(line);
this.scheduleFlush();
});
}
async start(sendLine: LiveLogSender): Promise<void> {
this.sender = sendLine;
this.enabled = true;
}
stop(): void {
this.enabled = false;
this.sender = null;
this.queue = [];
}
private scheduleFlush(): void {
if (this.flushing) {
return;
}
this.flushing = true;
Promise.resolve().then(async (): Promise<void> => {
try {
while (this.queue.length > 0) {
if (!this.enabled || this.sender == null) {
this.queue = [];
return;
}
const line = this.queue.shift() ?? "";
if (line == "") {
continue;
}
await this.sender(line).catch((): void => {});
}
} finally {
this.flushing = false;
if (this.enabled && this.queue.length > 0) {
this.scheduleFlush();
}
}
});
}
}