/** * Token bucket that may go into debt: a chunk that was already read is always * sent, and the stream stays paused until the debt is paid off. */ export class TokenBucket { readonly rate: number; readonly capacity: number; private readonly now: () => number; private tokens: number; private last: number; constructor(rate: number, capacity = rate, now = () => performance.now()) { this.rate = rate; this.capacity = capacity; this.now = now; this.tokens = capacity; this.last = now(); } take(amount: number): void { this.refill(); this.tokens -= amount; } available(): number { this.refill(); return this.tokens; } millisecondsUntilAvailable(): number { const tokens = this.available(); return tokens > 0 ? 0 : Math.ceil((-tokens / this.rate) * 1000); } private refill(): void { const now = this.now(); this.tokens = Math.min(this.capacity, this.tokens + ((now - this.last) / 1000) * this.rate); this.last = now; } }