import { setTimeout as sleep } from 'node:timers/promises' /** * Passes a byte stream on at most `bytesPerSecond` on average: a worker on a * line it shares (`edge:node --max-mbit`) reads its range slower, and TCP * holds the sender back. The first second's worth goes at once. */ export async function* throttle(stream: AsyncIterable | Iterable, bytesPerSecond: number): AsyncGenerator { const started = Date.now() let bytes = 0 for await (const piece of stream) { yield piece bytes += piece.byteLength const due = started + ((bytes - bytesPerSecond) / bytesPerSecond) * 1000 const wait = due - Date.now() if (wait > 0) await sleep(wait) } }