Files
Kaname/src/worker/throttle.ts
T
Pascal LinxweilerandClaude Opus 5.5 85af566b93 Downloads: speed limit in Settings
hf has no bandwidth option, so the worker pauses hf (SIGSTOP/SIGCONT) whenever it is ahead of a
token bucket over bytes on disk. The limit is shared by all running downloads and re-read every
5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:04:48 +02:00

33 lines
1.2 KiB
TypeScript

/**
* 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;
}
}