Skip to content
refs
History
43 lines · 1.3 KBRaw
1const MAX_BATCH = 8 * 1024;
2const FLUSH_MS = 250;
3
4export type LogSink = (step: number, text: string) => Promise<void>;
5
6/**
7 * Collects job output and sends it in batches of at most 8 KB, or every 250 ms. Sends run one at a time, in order,
8 * so the hub never stores a later batch before an earlier one. A failed send is logged and dropped; the job goes on.
9 */
10export class LogBatcher {
11 readonly #sink: LogSink;
12 #step = 0;
13 #buffer = "";
14 #timer: ReturnType<typeof setTimeout> | null = null;
15 #sending: Promise<void> = Promise.resolve();
16
17 constructor(sink: LogSink) {
18 this.#sink = sink;
19 }
20
21 write(step: number, text: string): void {
22 if (step !== this.#step) this.#send();
23 this.#step = step;
24 this.#buffer += text;
25 if (this.#buffer.length >= MAX_BATCH) this.#send();
26 else this.#timer ??= setTimeout(() => this.#send(), FLUSH_MS);
27 }
28
29 async flush(): Promise<void> {
30 this.#send();
31 await this.#sending;
32 }
33
34 #send(): void {
35 if (this.#timer) clearTimeout(this.#timer);
36 this.#timer = null;
37 if (!this.#buffer) return;
38 const step = this.#step;
39 const text = this.#buffer;
40 this.#buffer = "";
41 this.#sending = this.#sending.then(() => this.#sink(step, text)).catch((error) => console.error("log batch dropped", error));
42 }
43}