/** * Download speed limit as a token bucket over bytes on disk. Neither `hf download` nor hf_xet has a * bandwidth option (checked: huggingface_hub 2.1.1, hf_xet 1.6.0), so the worker pauses the hf * process (SIGSTOP/SIGCONT) whenever it got ahead of the limit. While hf is stopped its socket * buffers fill and TCP flow control holds the sender back, so the network rate follows. */ export class Throttle { private tokens = 0; private last: { t: number; bytes: number } | null = null; /** `burstSeconds`: how far ahead of the limit hf may run before it is paused. */ constructor( public limit: number, private burstSeconds = 1, ) {} /** Feed a (time ms, total bytes) sample; returns true while hf should be paused. */ update(t: number, bytes: number): boolean { const cap = this.limit * this.burstSeconds; if (!this.last) { this.last = { t, bytes }; this.tokens = cap; return false; } const dt = Math.max(0, t - this.last.t) / 1000; // Bytes can shrink when partial files are removed; that's not negative traffic. const used = Math.max(0, bytes - this.last.bytes); this.tokens = Math.min(cap, this.tokens + this.limit * dt) - used; this.last = { t, bytes }; return this.tokens < 0; } }