{"version":3,"file":"FlowControlledDataChannel.mjs","sources":["../../../../src/room/data-channel/FlowControlledDataChannel.ts"],"sourcesContent":["import { Mutex } from '@livekit/mutex';\nimport TypedPromise from '../../utils/TypedPromise';\nimport { UnexpectedConnectionState } from '../errors';\nimport type { DataChannelKind } from './types';\n\nexport interface FlowControlledDataChannelOptions {\n  kind: DataChannelKind;\n  /** Buffer level (bytes) at which blocked senders resume; armed as `bufferedAmountLowThreshold`. */\n  lowWaterMark: number;\n  /** Buffer level (bytes) above which senders block until the buffer drains to the low mark. */\n  highWaterMark: number;\n  /** Whether the owning engine has been closed — a closed engine rejects waiters immediately. */\n  isEngineClosed: () => boolean;\n  /**\n   * Notified when the buffer crosses the low-water mark in either direction (debounced: fires only\n   * on an actual change). Drives the engine's public DCBufferStatusChanged event.\n   */\n  onBufferStatusChanged?: (isLow: boolean) => void;\n}\n\n/**\n * Two-watermark flow control for one data channel kind.\n *\n * Owns the per-kind headroom gate: senders proceed freely while the buffer is at or below the\n * high-water mark and otherwise block — serialized FIFO through a mutex — until the browser's\n * `bufferedamountlow` event (armed at the low-water mark) signals the buffer has drained. The\n * serialization prevents woken senders from all refilling at once and overflowing the SCTP send\n * buffer (see livekit/client-sdk-js#1995).\n *\n * Waiters are parked on the channel object captured at wait entry. If that object stops being\n * current — replaced or torn down — its events may never fire again, so the owner must call\n * {@link invalidateWaiters}, which aborts parked waiters (releasing the gate); the next waiter\n * gets a fresh controller. {@link attach} and {@link detach} do this, and close the released\n * handle, as part of handle turnover.\n */\nexport class FlowControlledDataChannel {\n  readonly kind: DataChannelKind;\n\n  readonly lowWaterMark: number;\n\n  readonly highWaterMark: number;\n\n  protected isEngineClosed: () => boolean;\n\n  private onBufferStatusChanged?: (isLow: boolean) => void;\n\n  /** Last emitted low-water status; starts true (an empty buffer is below the mark). */\n  private bufferStatusLow = true;\n\n  private handle?: RTCDataChannel;\n\n  private headroomLock = new Mutex();\n\n  /** Cancels parked headroom waiters when the handle is replaced or torn down. */\n  private waiterAbortController = new AbortController();\n\n  constructor(opts: FlowControlledDataChannelOptions) {\n    this.kind = opts.kind;\n    this.lowWaterMark = opts.lowWaterMark;\n    this.highWaterMark = opts.highWaterMark;\n    this.isEngineClosed = opts.isEngineClosed;\n    this.onBufferStatusChanged = opts.onBufferStatusChanged;\n  }\n\n  /** The currently attached RTCDataChannel handle, if any. */\n  get channelHandle(): RTCDataChannel | undefined {\n    return this.handle;\n  }\n\n  /**\n   * Attaches the channel handle this wrapper controls. Replacing an existing handle closes it and\n   * rejects parked waiters — their events would never fire again on the abandoned object — and\n   * installs a fresh controller. Wrappers outlive their handles: this is the one place handle\n   * turnover happens, so a handle the wrapper lets go of is never left open, and stranding a\n   * waiter is structurally impossible.\n   */\n  attach(dc: RTCDataChannel) {\n    const old = this.handle;\n    this.handle = dc;\n    if (old && old !== dc) {\n      this.release(old, 'data channel replaced');\n    }\n  }\n\n  /** Detaches and closes the handle on teardown, rejecting parked waiters. */\n  detach(reason: string = 'data channel torn down') {\n    const old = this.handle;\n    this.handle = undefined;\n    if (old) {\n      this.release(old, reason);\n    }\n  }\n\n  /**\n   * Closes a handle the wrapper no longer controls. `close()` moves it to `closing` synchronously,\n   * so senders still holding it (queued on the headroom lock) fail the open check once they get\n   * the lock. Parked waiters are aborted directly instead of relying on the `close` event, which\n   * fires asynchronously, if at all (the spec lets `pc.close()` skip it). Strip any handlers that\n   * must not observe the close before calling this.\n   */\n  private release(dc: RTCDataChannel, reason: string) {\n    this.invalidateWaiters(reason);\n    dc.close();\n  }\n\n  protected getChannel(): RTCDataChannel | undefined {\n    return this.handle;\n  }\n\n  /**\n   * Whether the send buffer has room to accept more data (the send gate). Senders proceed while\n   * this is true and block once it goes false. Callers resolve the handle (and decide what an\n   * absent one means) before asking.\n   */\n  isBelowHighWaterMark(dc: RTCDataChannel): boolean {\n    // RTCDataChannel has no built-in high-water mark, so we compare against our static mark.\n    return dc.bufferedAmount <= this.highWaterMark;\n  }\n\n  /**\n   * Whether the send buffer has drained to its low-water mark. Drives the engine's public\n   * DCBufferStatusChanged event.\n   */\n  isBelowLowWaterMark(dc: RTCDataChannel): boolean {\n    // Read the channel's own threshold: it is tuned dynamically for the lossy channel.\n    return dc.bufferedAmount <= dc.bufferedAmountLowThreshold;\n  }\n\n  /**\n   * Acquires the headroom lock, resolving with the unlock function. Batch senders (the resume\n   * replay) hold it across all of their sends so no other sender can interleave, calling\n   * {@link waitForHeadroomWithoutLock} per message to respect flow control within the batch.\n   */\n  lockHeadroom(): Promise<() => void> {\n    return this.headroomLock.lock();\n  }\n\n  /**\n   * Resolves once the caller may send on `dc`: immediately while its send buffer is at or below\n   * the high-water mark, otherwise once the buffer has drained to the low-water mark (the\n   * `bufferedamountlow` event). Callers are serialized through the headroom lock so that, when\n   * the buffer drains, they refill it one at a time (up to the high-water mark) rather than all\n   * sending at once and overflowing the SCTP send buffer (see livekit/client-sdk-js#1995). The\n   * checks run inside the lock so queued callers proceed in FIFO order.\n   *\n   * The caller passes the handle it resolved before queueing, and the wait is against that one\n   * handle throughout: if it was replaced meanwhile, it has been closed, so the wait rejects\n   * rather than letting the caller send on the replacement out of turn.\n   */\n  async waitForHeadroomWithLock(dc: RTCDataChannel) {\n    const unlock = await this.lockHeadroom();\n    try {\n      await this.waitForHeadroomWithoutLock(dc);\n    } finally {\n      unlock();\n    }\n  }\n\n  /** Core wait of {@link waitForHeadroomWithLock}. The caller must hold the headroom lock. */\n  async waitForHeadroomWithoutLock(dc: RTCDataChannel) {\n    if (this.isEngineClosed()) {\n      throw new UnexpectedConnectionState('engine closed');\n    }\n    if (dc.readyState !== 'open') {\n      throw new UnexpectedConnectionState(`DataChannel ${this.kind} is ${dc.readyState}`);\n    }\n    if (this.isBelowHighWaterMark(dc)) {\n      return;\n    }\n    const abortSignal = this.waiterAbortController.signal;\n    await new TypedPromise<void, UnexpectedConnectionState>((resolve, reject) => {\n      const onBufferedAmountLow = () => {\n        cleanup();\n        resolve();\n      };\n      const onDCClose = () => {\n        cleanup();\n        reject(\n          new UnexpectedConnectionState(\n            `DataChannel ${this.kind} closed while draining the buffer`,\n          ),\n        );\n      };\n      const onAbort = () => {\n        cleanup();\n        reject(\n          new UnexpectedConnectionState(\n            `DataChannel ${this.kind} was replaced or torn down while waiting for headroom`,\n          ),\n        );\n      };\n      const cleanup = () => {\n        dc.removeEventListener('bufferedamountlow', onBufferedAmountLow);\n        dc.removeEventListener('close', onDCClose);\n        abortSignal.removeEventListener('abort', onAbort);\n      };\n      if (abortSignal.aborted) {\n        onAbort();\n        return;\n      }\n      dc.addEventListener('bufferedamountlow', onBufferedAmountLow);\n      // Proxy along any error caused by the data channel closing while we wait.\n      dc.addEventListener('close', onDCClose);\n      // The channel object we're parked on can be abandoned without ever firing another event\n      // (e.g. the engine recreating channels); the abort is our way out.\n      abortSignal.addEventListener('abort', onAbort);\n    });\n  }\n\n  /** Rejects all parked headroom waiters; the next waiter gets a fresh controller. */\n  invalidateWaiters(reason: string) {\n    this.waiterAbortController.abort(reason);\n    this.waiterAbortController = new AbortController();\n  }\n\n  /**\n   * Recomputes whether the buffer has drained to the low-water mark and, if that changed since the\n   * last check, notifies the status listener. Two independent triggers land here: a send (which\n   * raises the buffer) and the `bufferedamountlow` drain event (which lowers it) — the latter has\n   * no send to hang the work off, which is why this is a shared entry point rather than a tail of\n   * `send`.\n   */\n  refreshBufferStatus() {\n    const dc = this.getChannel();\n    if (!dc) {\n      return;\n    }\n    const isLow = this.isBelowLowWaterMark(dc);\n    if (isLow !== this.bufferStatusLow) {\n      this.bufferStatusLow = isLow;\n      this.onBufferStatusChanged?.(isLow);\n    }\n  }\n}\n"],"names":["FlowControlledDataChannel","constructor","opts","bufferStatusLow","headroomLock","Mutex","waiterAbortController","AbortController","kind","lowWaterMark","highWaterMark","isEngineClosed","onBufferStatusChanged","channelHandle","handle","attach","dc","old","release","detach","reason","undefined","invalidateWaiters","close","getChannel","isBelowHighWaterMark","bufferedAmount","isBelowLowWaterMark","bufferedAmountLowThreshold","lockHeadroom","lock","waitForHeadroomWithLock","unlock","waitForHeadroomWithoutLock","UnexpectedConnectionState","readyState","concat","abortSignal","signal","TypedPromise","resolve","reject","onBufferedAmountLow","cleanup","onDCClose","onAbort","removeEventListener","aborted","addEventListener","abort","refreshBufferStatus","isLow","_a","call"],"mappings":"8KAoBA;;;;;;;;;;;;;;AAcG;MACUA,yBAAyB,CAAA;EAqBpCC,WAAAA,CAAYC,IAAsC,EAAA;AAVlD;IACQ,IAAA,CAAAC,eAAe,GAAG,IAAI;AAItB,IAAA,IAAA,CAAAC,YAAY,GAAG,IAAIC,KAAK,EAAE;AAElC;AACQ,IAAA,IAAA,CAAAC,qBAAqB,GAAG,IAAIC,eAAe,EAAE;AAGnD,IAAA,IAAI,CAACC,IAAI,GAAGN,IAAI,CAACM,IAAI;AACrB,IAAA,IAAI,CAACC,YAAY,GAAGP,IAAI,CAACO,YAAY;AACrC,IAAA,IAAI,CAACC,aAAa,GAAGR,IAAI,CAACQ,aAAa;AACvC,IAAA,IAAI,CAACC,cAAc,GAAGT,IAAI,CAACS,cAAc;AACzC,IAAA,IAAI,CAACC,qBAAqB,GAAGV,IAAI,CAACU,qBAAqB;AACzD,EAAA;AAEA;EACA,IAAIC,aAAaA,GAAA;IACf,OAAO,IAAI,CAACC,MAAM;AACpB,EAAA;AAEA;;;;;;AAMG;EACHC,MAAMA,CAACC,EAAkB,EAAA;AACvB,IAAA,MAAMC,GAAG,GAAG,IAAI,CAACH,MAAM;IACvB,IAAI,CAACA,MAAM,GAAGE,EAAE;AAChB,IAAA,IAAIC,GAAG,IAAIA,GAAG,KAAKD,EAAE,EAAE;AACrB,MAAA,IAAI,CAACE,OAAO,CAACD,GAAG,EAAE,uBAAuB,CAAC;AAC5C,IAAA;AACF,EAAA;AAEA;AACAE,EAAAA,MAAMA,GAA0C;AAAA,IAAA,IAAzCC,6EAAiB,wBAAwB;AAC9C,IAAA,MAAMH,GAAG,GAAG,IAAI,CAACH,MAAM;IACvB,IAAI,CAACA,MAAM,GAAGO,S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