{"version":3,"file":"ReliableDataChannel.mjs","sources":["../../../../src/room/data-channel/ReliableDataChannel.ts"],"sourcesContent":["import type { NonSharedUint8Array } from '../../type-polyfills/non-shared-typed-arrays';\nimport { DataPacketBuffer } from '../../utils/dataPacketBuffer';\nimport { UnexpectedConnectionState } from '../errors';\nimport {\n  FlowControlledDataChannel,\n  type FlowControlledDataChannelOptions,\n} from './FlowControlledDataChannel';\n\nexport interface ReliableDataChannelOptions extends FlowControlledDataChannelOptions {\n  /**\n   * Whether sends should currently be deferred to the resume replay instead of hitting the wire\n   * (i.e. a reconnect attempt is underway). Read at send time so the reliable channel matches the\n   * engine's reconnect state without owning it.\n   */\n  isDeferringSends: () => boolean;\n}\n\n/**\n * The reliable channel: flow control plus delivery-across-resume semantics.\n *\n * Every packet gets a monotonic sequence (stamped into the protobuf by the caller before\n * serialization, via {@link nextSequence}) and is retained in a replay buffer until the channel's\n * `bufferedAmount` confirms it has been handed to the transport. Sends that land in a reconnect\n * window — or whose headroom wait is torn down transiently — are queued unsent and resolve;\n * {@link replay} delivers them (plus any unacked packets) after a resume. Only an engine close\n * rejects, because no replay is coming after that.\n */\nexport class ReliableDataChannel extends FlowControlledDataChannel {\n  private messageBuffer = new DataPacketBuffer();\n\n  private sequence = 1;\n\n  private isDeferringSends: () => boolean;\n\n  constructor(opts: ReliableDataChannelOptions) {\n    super(opts);\n    this.isDeferringSends = opts.isDeferringSends;\n  }\n\n  /**\n   * Claims the next packet sequence. The caller stamps it into the packet before serialization,\n   * then passes it back to {@link send} so the replay buffer stays keyed by wire sequence.\n   */\n  nextSequence(): number {\n    const sequence = this.sequence;\n    this.sequence += 1;\n    return sequence;\n  }\n\n  /**\n   * Sends prepared bytes with reliable semantics. Resolves once the packet has either been handed\n   * to the channel or queued for the resume replay; throws only when the engine is closed.\n   */\n  async send(msg: NonSharedUint8Array, sequence: number) {\n    if (this.isDeferringSends()) {\n      // A reconnect is already underway — queue for the resume replay instead of parking on a\n      // channel that is being torn down. The send resolves; delivery is deferred to the replay.\n      this.messageBuffer.push({ data: msg, sequence, sent: false });\n      return;\n    }\n\n    const dc = this.getChannel();\n    if (!dc) {\n      return;\n    }\n\n    try {\n      await this.waitForHeadroomWithLock(dc);\n    } catch (error) {\n      if (this.isEngineClosed()) {\n        // No replay is coming after an engine close — surface the failure.\n        throw error;\n      }\n      // Transient teardown (the channel closed or was replaced while we waited): the reliable\n      // channel promises delivery across resume, so queue the packet for the replay instead of\n      // rejecting a send the app can't meaningfully retry. This also keeps the order: a send\n      // queued behind one aborted by a replacement fails the same way (the old handle is closed),\n      // so it can't reach the replacement ahead of the lower sequence the replay will deliver.\n      this.messageBuffer.push({ data: msg, sequence, sent: false });\n      return;\n    }\n\n    if (this.isDeferringSends()) {\n      // A reconnect began while we waited for headroom — same deal as above.\n      this.messageBuffer.push({ data: msg, sequence, sent: false });\n      return;\n    }\n\n    this.messageBuffer.push({ data: msg, sequence, sent: true });\n    dc.send(msg);\n    this.refreshBufferStatus();\n  }\n\n  /**\n   * Replays the buffered backlog after a resume: drops everything the server acked\n   * (`lastMessageSeq`), then re-sends the rest in order. The headroom lock is held across the\n   * whole replay — releasing it between messages would let a concurrent send (whose newer\n   * sequence was already assigned before it queued on the lock) hit the wire mid-replay, and\n   * receivers would then discard the remaining lower-sequence resent messages as duplicates.\n   */\n  async replay(lastMessageSeq: number) {\n    if (!this.getChannel()) {\n      return;\n    }\n    this.messageBuffer.popToSequence(lastMessageSeq);\n    const unlock = await this.lockHeadroom();\n    try {\n      // Resolved only once the lock is held: the handle can be replaced while the replay waits\n      // for it.\n      const dc = this.getChannel();\n      if (!dc) {\n        throw new UnexpectedConnectionState(`DataChannel not found, kind: ${this.kind}`);\n      }\n      // Everything left after the ack cutoff must be re-handed to the current channel.\n      this.messageBuffer.markAllUnsent();\n      // Drain in passes, re-scanning the live buffer each time: a send that arrives (deferred,\n      // sent:false) during our own awaits appends after this pass started, so we pick it up on\n      // the next one. Mark each packet only once we've actually handed it to the channel — a\n      // blanket \"mark all sent\" would flip such a late arrival to sent without transmitting it,\n      // and a later alignBufferedAmount would then drop it for good. If the loop throws\n      // mid-drain, unsent entries keep their flag and the next replay picks them up.\n      for (\n        let batch = this.messageBuffer.getUnsent();\n        batch.length > 0;\n        batch = this.messageBuffer.getUnsent()\n      ) {\n        for (const item of batch) {\n          // Respect flow control on resume too, so a large resend doesn't overflow the buffer.\n          // Against the handle resolved under the lock: if it is replaced mid-replay (another\n          // resume), it has been closed, so this throws and that resume's replay picks up the\n          // entries still flagged unsent.\n          await this.waitForHeadroomWithoutLock(dc);\n          dc.send(item.data);\n          this.messageBuffer.markSent(item);\n        }\n      }\n    } finally {\n      unlock();\n    }\n    this.refreshBufferStatus();\n  }\n\n  /**\n   * Before recomputing status, trim packets the transport has now delivered — a send or a drain\n   * may have acked buffered packets, and the replay buffer is keyed off the channel's buffered\n   * bytes.\n   */\n  override refreshBufferStatus() {\n    const dc = this.channelHandle;\n    if (dc) {\n      this.messageBuffer.alignBufferedAmount(dc.bufferedAmount);\n    }\n    super.refreshBufferStatus();\n  }\n\n  /**\n   * Drops all replay state and restarts sequencing. Only valid on a full reconnect, where the\n   * session (and the receivers' sequence tracking) starts over.\n   */\n  reset() {\n    this.messageBuffer = new DataPacketBuffer();\n    this.sequence = 1;\n  }\n}\n"],"names":["ReliableDataChannel","FlowControlledDataChannel","constructor","opts","messageBuffer","DataPacketBuffer","sequence","isDeferringSends","nextSequence","send","msg","push","data","sent","dc","getChannel","waitForHeadroomWithLock","error","isEngineClosed","refreshBufferStatus","replay","lastMessageSeq","popToSequence","unlock","lockHeadroom","UnexpectedConnectionState","concat","kind","markAllUnsent","batch","getUnsent","length","item","waitForHeadroomWithoutLock","markSent","channelHandle","alignBufferedAmount","bufferedAmount","reset"],"mappings":"4NAiBA;;;;;;;;;AASG;AACG,MAAOA,mBAAoB,SAAQC,yBAAyB,CAAA;EAOhEC,WAAAA,CAAYC,IAAgC,EAAA;IAC1C,KAAK,CAACA,IAAI,CAAC;AAPL,I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