Files
Multi-Hoster-Upload/lib/throttle.js
SucukdeluxeandClaude Opus 5.5 d37e86690f
CI / verify (push) Canceled after 0s
Keep upload speed limits at the configured decimal MB/s
The shared upload limiter started with a full second of tokens and refilled
up to one second during short idle gaps, so new uploads could briefly send
almost twice the limit. In a parallel-upload test it released 3.87 MB in one
second at a 2 MB/s limit. Uploads now reserve send time on one shared
schedule with at most a 200 ms burst and exact waits.

Speeds and limits used 1024-based kB and MB while being shown as kB/s and
MB/s, so a limit of 100 meant 104.9 MB/s. Limits, measured speeds, ETA and
the speed graph now use 1 MB = 1,000,000 bytes. Saved limits are converted
once so the displayed value stays the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:26:01 +02:00

43 lines
1.4 KiB
JavaScript

/**
* Shared upload rate limiter. Every consumed byte reserves send time at the
* configured rate, so concurrent uploads together never exceed it. Only a
* short burst (burstMs) may be sent ahead after idle time.
* maxBytesPerSec = 0 means unlimited (passthrough).
*/
class Throttle {
constructor(maxBytesPerSec, options = {}) {
this.maxBps = maxBytesPerSec || 0;
this.burstMs = Math.max(0, Number(options.burstMs ?? 200));
this.now = typeof options.now === 'function' ? options.now : () => Date.now();
this.nextFreeAt = this.now();
}
async consume(bytes, signal) {
if (this.maxBps <= 0 || !(bytes > 0)) return;
if (signal && signal.aborted) return;
const now = this.now();
const start = Math.max(this.nextFreeAt, now - this.burstMs);
this.nextFreeAt = start + (bytes * 1000) / this.maxBps;
const wait = start - now;
if (wait <= 0) return;
await new Promise((resolve) => {
const timer = setTimeout(done, wait);
function done() {
clearTimeout(timer);
if (signal) signal.removeEventListener('abort', done);
resolve();
}
if (signal) signal.addEventListener('abort', done, { once: true });
});
}
updateRate(maxBytesPerSec) {
const next = maxBytesPerSec || 0;
if (next === this.maxBps) return;
this.maxBps = next;
this.nextFreeAt = Math.min(this.nextFreeAt, this.now() + this.burstMs);
}
}
module.exports = Throttle;