LiveLogService.uts 1.28 KB
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();
				}
			}
		});
	}
}