diff --git a/packages/webrtc/src/serial-send.ts b/packages/webrtc/src/serial-send.ts new file mode 100644 index 0000000..d656415 --- /dev/null +++ b/packages/webrtc/src/serial-send.ts @@ -0,0 +1,13 @@ +/** Serialize encryption with transmission, bounded even when the transport stalls. */ +export class SerialSend { + private tail: Promise = Promise.resolve() + private bytes = 0 + private count = 0 + async run(bytes: number, send: () => Promise): Promise { + if (this.bytes + bytes > 8 * 1024 * 1024 || this.count >= 256) throw new Error('Encrypted send queue exceeds its limit') + this.bytes += bytes; this.count += 1 + const task = this.tail.then(send) + this.tail = task.catch(() => undefined) + try { await task } finally { this.bytes -= bytes; this.count -= 1 } + } +}