const MAX_BATCH = 8 * 1024; const FLUSH_MS = 250; export type LogSink = (step: number, text: string) => Promise; /** * 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, * so the hub never stores a later batch before an earlier one. A failed send is logged and dropped; the job goes on. */ export class LogBatcher { readonly #sink: LogSink; #step = 0; #buffer = ""; #timer: ReturnType | null = null; #sending: Promise = Promise.resolve(); constructor(sink: LogSink) { this.#sink = sink; } write(step: number, text: string): void { if (step !== this.#step) this.#send(); this.#step = step; this.#buffer += text; if (this.#buffer.length >= MAX_BATCH) this.#send(); else this.#timer ??= setTimeout(() => this.#send(), FLUSH_MS); } async flush(): Promise { this.#send(); await this.#sending; } #send(): void { if (this.#timer) clearTimeout(this.#timer); this.#timer = null; if (!this.#buffer) return; const step = this.#step; const text = this.#buffer; this.#buffer = ""; this.#sending = this.#sending.then(() => this.#sink(step, text)).catch((error) => console.error("log batch dropped", error)); } }