{"version":3,"file":"LossyDataChannel.mjs","sources":["../../../../src/room/data-channel/LossyDataChannel.ts"],"sourcesContent":["import log from '../../logger';\nimport type { NonSharedUint8Array } from '../../type-polyfills/non-shared-typed-arrays';\nimport CriticalTimers from '../timers';\nimport {\n  FlowControlledDataChannel,\n  type FlowControlledDataChannelOptions,\n} from './FlowControlledDataChannel';\n\nexport interface LossyDataChannelOptions extends FlowControlledDataChannelOptions {\n  /**\n   * What to do with a send while the buffer is full: `drop` discards it to keep latency bounded\n   * (the classic lossy channel), `wait` backpressures the producer until there is headroom (the\n   * data-track channel, whose producer decides what to skip at frame granularity).\n   */\n  bufferFullBehavior: 'drop' | 'wait';\n  /** Sends are silently discarded while this is true (a reconnect attempt is underway). */\n  shouldSkipSends: () => boolean;\n}\n\n/**\n * A lossy channel: flow control plus a per-instance full-buffer policy.\n *\n * Each instance owns its own byterate stat, drop counter, and (when tuning is started) the\n * dynamic `bufferedAmountLowThreshold` adjustment that keeps the drop gate at roughly 100ms of\n * buffered latency. Keeping these per instance is what prevents one channel's traffic from\n * steering another channel's policy.\n */\nexport class LossyDataChannel extends FlowControlledDataChannel {\n  private bufferFullBehavior: 'drop' | 'wait';\n\n  private shouldSkipSends: () => boolean;\n\n  private statCurrentBytes = 0;\n\n  private statByterate = 0;\n\n  private statInterval: ReturnType<typeof setInterval> | undefined;\n\n  private dropCount = 0;\n\n  constructor(opts: LossyDataChannelOptions) {\n    super(opts);\n    this.bufferFullBehavior = opts.bufferFullBehavior;\n    this.shouldSkipSends = opts.shouldSkipSends;\n  }\n\n  /** Sends prepared bytes with this channel's full-buffer policy (drop or wait). */\n  async send(msg: NonSharedUint8Array) {\n    const dc = this.getChannel();\n    if (!dc) {\n      return;\n    }\n    // Depending on the channel's policy, either drop or wait for the buffer to drain below the\n    // high-water mark before continuing.\n    switch (this.bufferFullBehavior) {\n      case 'wait':\n        if (!this.isBelowHighWaterMark(dc)) {\n          try {\n            await this.waitForHeadroomWithLock(dc);\n          } catch (error) {\n            if (this.isEngineClosed()) {\n              throw error;\n            }\n            // The channel closed or was replaced while this send waited. The replacement may\n            // still be connecting, so drop the packet, as sends during a reconnect are.\n            return;\n          }\n        }\n        break;\n      case 'drop':\n        // We check against the actual threshold on the DC here, as it is tuned dynamically.\n        if (!this.isBelowLowWaterMark(dc)) {\n          // Drop messages to reduce latency\n          this.dropCount += 1;\n          if (this.dropCount % 100 === 0) {\n            log.warn(`dropping lossy data channel messages, total dropped: ${this.dropCount}`);\n          }\n          return;\n        }\n    }\n    this.statCurrentBytes += msg.byteLength;\n\n    if (this.shouldSkipSends()) {\n      return;\n    }\n\n    try {\n      dc.send(msg);\n      this.refreshBufferStatus();\n    } catch (error: unknown) {\n      // Preserve prior surface behaviour: a send that fails because the channel is closing is\n      // logged, not thrown, so lossy/data-track sends don't reject during teardown windows.\n      if (error instanceof TypeError) {\n        log.error(error);\n      } else {\n        throw error;\n      }\n    }\n  }\n\n  /**\n   * Starts the once-per-second adjustment of the channel's `bufferedAmountLowThreshold` to the\n   * observed byterate, keeping the drop gate at roughly 100ms of buffered latency (clamped to\n   * the watermarks). Restarts cleanly if already running.\n   */\n  startThresholdTuning() {\n    this.stopThresholdTuning();\n    this.statInterval = CriticalTimers.setInterval(() => {\n      this.statByterate = this.statCurrentBytes;\n      this.statCurrentBytes = 0;\n\n      const dc = this.getChannel();\n      if (dc) {\n        // control buffered latency to ~100ms\n        const threshold = this.statByterate / 10;\n        dc.bufferedAmountLowThreshold = Math.min(\n          Math.max(threshold, this.lowWaterMark),\n          this.highWaterMark,\n        );\n      }\n    }, 1000);\n  }\n\n  /** Stops the threshold tuning and resets the stats and drop counter. */\n  stopThresholdTuning() {\n    this.statByterate = 0;\n    this.statCurrentBytes = 0;\n    if (this.statInterval) {\n      CriticalTimers.clearInterval(this.statInterval);\n      this.statInterval = undefined;\n    }\n    this.dropCount = 0;\n  }\n}\n"],"names":["LossyDataChannel","FlowControlledDataChannel","constructor","opts","statCurrentBytes","statByterate","dropCount","bufferFullBehavior","shouldSkipSends","send","msg","dc","getChannel","isBelowHighWaterMark","waitForHeadroomWithLock","error","isEngineClosed","isBelowLowWaterMark","log","warn","concat","byteLength","refreshBufferStatus","TypeError","startThresholdTuning","stopThresholdTuning","statInterval","CriticalTimers","setInterval","threshold","bufferedAmountLowThreshold","Math","min","max","lowWaterMark","highWaterMark","clearInterval","undefined"],"mappings":"4LAmBA;;;;;;;AAOG;AACG,MAAOA,gBAAiB,SAAQC,yBAAyB,CAAA;EAa7DC,WAAAA,CAAYC,IAA6B,EAAA;IACvC,KAAK,CAACA,IAAI,CAAC;IATL,IAAA,CAAAC,gBAAgB,GAAG,CAAC;IAEpB,IAAA,CAAAC,YAAY,GAAG,CAAC;IAIhB,IAAA,CAAAC,SAAS,GAAG,CAAC;AAInB,IAAA,IAAI,CAACC,kBAAkB,GAAGJ,IAAI,CAACI,kBAAkB;AACjD,IAAA,IAAI,CAACC,eAAe,GAAGL,IAAI,CAACK,eAAe;AAC7C,EAAA;AAEA;EACMC,IAAIA,CAACC,GAAwB,EAAA;;AACjC,MAAA,MAAMC,EAAE,GAAG,IAAI,CAACC,UAAU,EAAE;MAC5B,IAAI,CAACD,EAAE,EAAE;AACP,QAAA;AACF,MAAA;AACA;AACA;MACA,QAAQ,IAAI,CAACJ,kBAAkB;AAC7B,QAAA,KAAK,MAAM;AACT,UAAA,IAAI,CAAC,IAAI,CAACM,oBAAoB,CAACF,EAAE,CAAC,EAAE;YAClC,IAAI;AACF,cAAA,MAAM,IAAI,CAACG,uBAAuB,CAACH,EAAE,CAAC;YACxC,CAAC,CAAC,OAAOI,KAAK,EAAE;AACd,cAAA,IAAI,IAAI,CAACC,cAAc,EAAE,EAAE;AACzB,gBAAA,MAAMD,KAAK;AACb,cAAA;AACA;AACA;AACA,cAAA;AACF,YAAA;AACF,UAAA;AACA,UAAA;AACF,QAAA,KAAK,MAAM;AACT;AACA,UAAA,IAAI,CAAC,IAAI,CAACE,mBAAmB,CAACN,EAAE,CAAC,EAAE;A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