Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

24.1 KB
Raw Blame
import type { CollabIceCandidateType } from '../types/multiplayer';

export type CollabTransportKind = 'ws' | 'webrtc-host' | 'webrtc-guest';

export interface CollabSendOptions {
  /**
   * Hint that this payload is loss-tolerant / low-latency (e.g., cursor move or follow-camera).
   * Transports with an unordered unreliable DataChannel route it there and drop it immediately
   * under backpressure instead of queuing behind reliable traffic.
   */
  ephemeral?: boolean;
}

export interface ICollabTransport {
  readonly kind: CollabTransportKind;
  isOpen(): boolean;
  getBufferedAmount(): number;
  sendText(text: string, options?: CollabSendOptions): void;
  sendBinary(data: ArrayBuffer | Uint8Array, options?: CollabSendOptions): void;
  sendBinaryTo?(
    targetPeerId: string | number,
    data: ArrayBuffer | Uint8Array,
    options?: CollabSendOptions
  ): void;
  /** Optional Host Hub lifecycle hooks for snapshot isolation and incremental reconnect catch-up. */
  beginPeerSnapshot?(targetPeerId: string | number): number | void;
  finishPeerSnapshot?(targetPeerId: string | number, snapshotSeq?: number): void;
  canIncrementalCatchUp?(sinceSeq: number): boolean;
  replayIncrementalToPeer?(targetPeerId: string | number, sinceSeq: number): boolean;
  /** Optional network diagnostics hooks. */
  getDroppedEphemeralCount?(): number;
  getActiveIceCandidateType?(): Promise<CollabIceCandidateType | null>;
  close(): void;
  onTextMessage(handler: (text: string) => void): () => void;
  onBinaryMessage(handler: (data: ArrayBuffer) => void): () => void;
  onClose(handler: (reason?: string) => void): () => void;
  onError(handler: (err: Error | Event) => void): () => void;
}

/**
 * Lightweight binary framing/chunking header for RTCDataChannel transport.
 *
 * Frame layout (16 bytes header + payload slice):
 *   [0..1]   Magic bytes: 'I' (0x49), 'C' (0x43)  (distinct from 'I','N' wire packets)
 *   [2]      Payload kind: 0x01 = UTF-8 JSON text, 0x02 = raw binary ArrayBuffer
 *   [3]      Flags (reserved, 0x00)
 *   [4..7]   messageId (Uint32 LE)
 *   [8..11]  chunkIndex (Uint32 LE, 0 .. totalChunks - 1)
 *   [12..15] totalChunks (Uint32 LE, 1 .. MAX_CHUNKS_PER_MESSAGE)
 *   [16..]   Chunk payload bytes (<= maxChunkPayloadBytes, default 48 KB)
 */
export const CHUNK_MAGIC_0 = 0x49; // 'I'
export const CHUNK_MAGIC_1 = 0x43; // 'C'
export const CHUNK_KIND_TEXT = 0x01;
export const CHUNK_KIND_BINARY = 0x02;
export const CHUNK_HEADER_BYTES = 16;

/** Safe default chunk payload size (48 KB) well below Android WebView / browser SCTP limits. */
export const DEFAULT_CHUNK_PAYLOAD_BYTES = 48 * 1024;
/** Maximum reassembled message size (16 MB, matching multiplayerService binary ceiling). */
export const MAX_REASSEMBLED_MESSAGE_BYTES = 16 * 1024 * 1024;
/** Safety cap on chunk count per message. */
export const MAX_CHUNKS_PER_MESSAGE = 1024;
/** Maximum concurrent incomplete reassembly buffers per peer. */
export const MAX_INFLIGHT_REASSEMBLY = 64;
/** Timeout before stale incomplete chunk buffers are evicted. */
export const REASSEMBLY_TIMEOUT_MS = 30_000;

export type ReassembledTransportMessage =
  | { kind: 'text'; text: string }
  | { kind: 'binary'; data: ArrayBuffer };

const sharedTextEncoder = new TextEncoder();
const sharedTextDecoder = new TextDecoder();

export function toUint8Array(data: ArrayBuffer | Uint8Array): Uint8Array {
  return data instanceof Uint8Array ? data : new Uint8Array(data);
}

/**
 * Splits a text (JSON) or binary ('IN...') payload into 1 or more framed chunks
 * sized <= `maxChunkPayloadBytes` (+ 16 byte header).
 */
export function encodeTransportFrames(
  kind: 'text' | 'binary',
  payload: string | ArrayBuffer | Uint8Array,
  messageId: number,
  maxChunkPayloadBytes: number = DEFAULT_CHUNK_PAYLOAD_BYTES
): Uint8Array[] {
  const safeChunkSize = Math.max(256, Math.min(256 * 1024, Math.floor(maxChunkPayloadBytes)));
  const rawBytes =
    kind === 'text'
      ? sharedTextEncoder.encode(typeof payload === 'string' ? payload : '')
      : toUint8Array(payload as ArrayBuffer | Uint8Array);

  if (rawBytes.byteLength > MAX_REASSEMBLED_MESSAGE_BYTES) {
    throw new Error(
      `Transport payload exceeds ${MAX_REASSEMBLED_MESSAGE_BYTES} byte safety ceiling`
    );
  }

  const totalChunks = Math.max(1, Math.ceil(rawBytes.byteLength / safeChunkSize));
  if (totalChunks > MAX_CHUNKS_PER_MESSAGE) {
    throw new Error(`Transport payload requires too many chunks (${totalChunks})`);
  }

  const kindByte = kind === 'text' ? CHUNK_KIND_TEXT : CHUNK_KIND_BINARY;
  const msgIdU32 = messageId >>> 0;
  const frames: Uint8Array[] = new Array(totalChunks);

  for (let i = 0; i < totalChunks; i++) {
    const start = i * safeChunkSize;
    const end = Math.min(rawBytes.byteLength, start + safeChunkSize);
    const sliceLen = end - start;
    const frame = new Uint8Array(CHUNK_HEADER_BYTES + sliceLen);
    const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);

    frame[0] = CHUNK_MAGIC_0;
    frame[1] = CHUNK_MAGIC_1;
    frame[2] = kindByte;
    frame[3] = 0;
    view.setUint32(4, msgIdU32, true);
    view.setUint32(8, i >>> 0, true);
    view.setUint32(12, totalChunks >>> 0, true);

    if (sliceLen > 0) {
      frame.set(rawBytes.subarray(start, end), CHUNK_HEADER_BYTES);
    }
    frames[i] = frame;
  }

  return frames;
}

interface PendingAssembly {
  kindByte: number;
  totalChunks: number;
  receivedCount: number;
  totalBytes: number;
  chunks: Array<Uint8Array | undefined>;
  createdAt: number;
}

/**
 * Stateful per-peer chunk reassembler with bounds, duplicate, and timeout protection.
 */
export class ChunkReassembler {
  private pending = new Map<number, PendingAssembly>();
  private readonly maxMessageBytes: number;
  private readonly maxInflight: number;
  private readonly timeoutMs: number;

  constructor(options?: {
    maxMessageBytes?: number;
    maxInflight?: number;
    timeoutMs?: number;
  }) {
    this.maxMessageBytes = options?.maxMessageBytes ?? MAX_REASSEMBLED_MESSAGE_BYTES;
    this.maxInflight = options?.maxInflight ?? MAX_INFLIGHT_REASSEMBLY;
    this.timeoutMs = options?.timeoutMs ?? REASSEMBLY_TIMEOUT_MS;
  }

  public getPendingCount(): number {
    return this.pending.size;
  }

  public clear(): void {
    this.pending.clear();
  }

  public pruneExpired(nowMs: number = Date.now()): void {
    for (const [id, entry] of this.pending.entries()) {
      if (nowMs - entry.createdAt > this.timeoutMs) {
        this.pending.delete(id);
      }
    }
  }

  public pushFrame(
    frameData: ArrayBuffer | Uint8Array,
    nowMs: number = Date.now()
  ): ReassembledTransportMessage | null {
    const bytes = toUint8Array(frameData);
    if (bytes.byteLength < CHUNK_HEADER_BYTES) return null;
    if (bytes[0] !== CHUNK_MAGIC_0 || bytes[1] !== CHUNK_MAGIC_1) return null;

    const kindByte = bytes[2];
    if (kindByte !== CHUNK_KIND_TEXT && kindByte !== CHUNK_KIND_BINARY) return null;

    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const messageId = view.getUint32(4, true);
    const chunkIndex = view.getUint32(8, true);
    const totalChunks = view.getUint32(12, true);

    if (
      totalChunks === 0 ||
      totalChunks > MAX_CHUNKS_PER_MESSAGE ||
      chunkIndex >= totalChunks
    ) {
      return null;
    }

    const payloadSlice = bytes.subarray(CHUNK_HEADER_BYTES);
    if (payloadSlice.byteLength > this.maxMessageBytes) {
      this.pending.delete(messageId);
      return null;
    }

    // Fast path for single-chunk messages (avoids pending map overhead for strokes/cursors)
    if (totalChunks === 1) {
      this.pending.delete(messageId);
      if (kindByte === CHUNK_KIND_TEXT) {
        return { kind: 'text', text: sharedTextDecoder.decode(payloadSlice) };
      }
      const copy = new Uint8Array(payloadSlice.byteLength);
      copy.set(payloadSlice);
      return { kind: 'binary', data: copy.buffer };
    }

    let entry = this.pending.get(messageId);
    if (!entry) {
      this.pruneExpired(nowMs);
      if (this.pending.size >= this.maxInflight) {
        const oldestKey = this.pending.keys().next().value;
        if (oldestKey !== undefined) {
          this.pending.delete(oldestKey);
        }
      }
      entry = {
        kindByte,
        totalChunks,
        receivedCount: 0,
        totalBytes: 0,
        chunks: new Array<Uint8Array | undefined>(totalChunks),
        createdAt: nowMs,
      };
      this.pending.set(messageId, entry);
    } else if (entry.totalChunks !== totalChunks || entry.kindByte !== kindByte) {
      // Mismatched header for an in-flight messageId — discard corrupt buffer
      this.pending.delete(messageId);
      return null;
    }

    // Ignore duplicate chunk indices safely
    if (entry.chunks[chunkIndex] !== undefined) {
      return null;
    }

    const nextTotalBytes = entry.totalBytes + payloadSlice.byteLength;
    if (nextTotalBytes > this.maxMessageBytes) {
      this.pending.delete(messageId);
      return null;
    }

    const chunkCopy = new Uint8Array(payloadSlice.byteLength);
    chunkCopy.set(payloadSlice);
    entry.chunks[chunkIndex] = chunkCopy;
    entry.receivedCount += 1;
    entry.totalBytes = nextTotalBytes;

    if (entry.receivedCount < entry.totalChunks) {
      return null;
    }

    this.pending.delete(messageId);

    const combined = new Uint8Array(entry.totalBytes);
    let offset = 0;
    for (let i = 0; i < entry.totalChunks; i++) {
      const part = entry.chunks[i];
      if (!part) return null;
      combined.set(part, offset);
      offset += part.byteLength;
    }

    if (entry.kindByte === CHUNK_KIND_TEXT) {
      return { kind: 'text', text: sharedTextDecoder.decode(combined) };
    }
    return { kind: 'binary', data: combined.buffer };
  }
}

/**
 * Helper to send a framed text or binary payload over an open RTCDataChannel.
 */
export function sendFramedOverDataChannel(
  dc: Pick<RTCDataChannel, 'readyState' | 'send'>,
  kind: 'text' | 'binary',
  payload: string | ArrayBuffer | Uint8Array,
  nextMessageId: () => number,
  maxChunkPayloadBytes: number = DEFAULT_CHUNK_PAYLOAD_BYTES
): boolean {
  if (dc.readyState !== 'open') return false;
  const frames = encodeTransportFrames(kind, payload, nextMessageId(), maxChunkPayloadBytes);
  for (const frame of frames) {
    dc.send(frame as unknown as ArrayBuffer);
  }
  return true;
}

const WIRE_BINARY_MAGIC_0 = 0x49; // 'I'
const WIRE_BINARY_MAGIC_1 = 0x4e; // 'N'
const WIRE_CODE_CURSOR_MOVE = 0x05;
const WIRE_CODE_CAMERA_SYNC = 0x0a;
const WIRE_CODE_PING = 0x0e;
const WIRE_CODE_PONG = 0x0f;

/**
 * Inspects an InkStudio binary wire packet ('I','N', opcode, ...) to determine
 * whether it is an ephemeral low-latency packet eligible for unordered/unreliable delivery.
 */
export function isEphemeralWireBinary(data: ArrayBuffer | Uint8Array): boolean {
  const bytes = toUint8Array(data);
  if (
    bytes.byteLength < 3 ||
    bytes[0] !== WIRE_BINARY_MAGIC_0 ||
    bytes[1] !== WIRE_BINARY_MAGIC_1
  ) {
    return false;
  }
  const opcode = bytes[2];
  return (
    opcode === WIRE_CODE_CURSOR_MOVE ||
    opcode === WIRE_CODE_CAMERA_SYNC ||
    opcode === WIRE_CODE_PING ||
    opcode === WIRE_CODE_PONG
  );
}

/**
 * Queries `RTCPeerConnection.getStats()` to classify the active nominated ICE candidate pair
 * (`host` | `srflx` | `prflx` | `relay` | `unknown`). Gracefully returns `null` when unavailable.
 */
export async function queryPeerConnectionIceCandidateType(
  pc: RTCPeerConnection | null | undefined
): Promise<CollabIceCandidateType | null> {
  if (!pc || typeof pc.getStats !== 'function') return null;
  try {
    const stats = await pc.getStats();
    if (!stats || typeof stats.forEach !== 'function') return null;

    let selectedPairId: string | null = null;
    const pairs: Array<Record<string, unknown>> = [];
    const candidates = new Map<string, Record<string, unknown>>();

    stats.forEach((report: Record<string, unknown>, key?: string) => {
      const type = report.type;
      const reportId =
        typeof report.id === 'string' ? report.id : typeof key === 'string' ? key : null;
      if (type === 'transport' && typeof report.selectedCandidatePairId === 'string') {
        selectedPairId = report.selectedCandidatePairId;
      } else if (type === 'candidate-pair') {
        pairs.push(reportId && !report.id ? { ...report, id: reportId } : report);
      } else if (type === 'local-candidate' || type === 'remote-candidate') {
        if (reportId) {
          candidates.set(reportId, report);
        }
      }
    });

    const activePair =
      (selectedPairId ? pairs.find((p) => p.id === selectedPairId) : undefined) ??
      pairs.find((p) => p.state === 'succeeded' && p.nominated === true) ??
      pairs.find((p) => p.state === 'succeeded');
    if (!activePair) return null;

    const normalizeCandType = (raw: unknown): CollabIceCandidateType | null => {
      if (raw === 'host' || raw === 'srflx' || raw === 'prflx' || raw === 'relay') {
        return raw;
      }
      return null;
    };

    const localCand =
      typeof activePair.localCandidateId === 'string'
        ? candidates.get(activePair.localCandidateId)
        : undefined;
    const remoteCand =
      typeof activePair.remoteCandidateId === 'string'
        ? candidates.get(activePair.remoteCandidateId)
        : undefined;

    const localType = normalizeCandType(localCand?.candidateType);
    const remoteType = normalizeCandType(remoteCand?.candidateType);
    if (localType === 'relay' || remoteType === 'relay') return 'relay';
    if (localType === 'srflx' || remoteType === 'srflx') return 'srflx';
    if (localType === 'prflx' || remoteType === 'prflx') return 'prflx';
    if (localType === 'host' || remoteType === 'host') return 'host';
    return 'unknown';
  } catch {
    return null;
  }
}

/** Low-water threshold configured on RTCDataChannel.bufferedAmountLowThreshold (256 KB). */
export const DC_BUFFERED_AMOUNT_LOW_THRESHOLD = 256 * 1024;
/** Soft ceiling above which ephemeral frames (cursors / follow-camera) are dropped immediately (128 KB). */
export const DC_EPHEMERAL_SOFT_LIMIT = 128 * 1024;
/** High-water mark above which reliable frames queue in FIFO order instead of overflowing SCTP (1 MB). */
export const DC_RELIABLE_HIGH_WATER_MARK = 1024 * 1024;
/** Hard safety ceiling on per-peer queued reliable bytes before disconnecting a wedged peer (16 MB). */
export const DC_RELIABLE_QUEUE_HARD_LIMIT = 16 * 1024 * 1024;
/** Maximum prolonged stall duration with zero drain progress before evicting a wedged peer (30 s). */
export const DC_STALL_TIMEOUT_MS = 30_000;
/** Timer fallback interval for mock/WebView DataChannels where bufferedamountlow may not fire. */
export const DC_FALLBACK_POLL_MS = 25;

export interface DataChannelSendQueueOptions {
  bufferedAmountLowThreshold?: number;
  ephemeralSoftLimit?: number;
  reliableHighWaterMark?: number;
  reliableQueueHardLimit?: number;
  stallTimeoutMs?: number;
  fallbackPollMs?: number;
  onOverflow?: (reason: string) => void;
}

/**
 * Per-connection outbound DataChannel scheduler supporting:
 *  - Optional dual-channel routing (unordered/unreliable ephemeral channel + reliable ordered channel)
 *  - Immediate drop of ephemeral frames under backpressure
 *  - Bounded FIFO queuing and bufferedamountlow (+ timer fallback) draining for reliable frames
 *  - Hard ceiling & prolonged-stall eviction for wedged peers
 */
export class DataChannelSendQueue {
  private reliableDc: RTCDataChannel | null = null;
  private reliableHasEventListener = false;
  private ephemeralDc: RTCDataChannel | null = null;

  private queue: Uint8Array[] = [];
  private queueHead = 0;
  private queuedBytes = 0;
  private droppedEphemeralCount = 0;
  private drainTimer: ReturnType<typeof setTimeout> | null = null;
  private stallStartedAt: number | null = null;

  private readonly bufferedAmountLowThreshold: number;
  private readonly ephemeralSoftLimit: number;
  private readonly reliableHighWaterMark: number;
  private readonly reliableQueueHardLimit: number;
  private readonly stallTimeoutMs: number;
  private readonly fallbackPollMs: number;
  private readonly onOverflow?: (reason: string) => void;

  constructor(options?: DataChannelSendQueueOptions) {
    this.bufferedAmountLowThreshold =
      options?.bufferedAmountLowThreshold ?? DC_BUFFERED_AMOUNT_LOW_THRESHOLD;
    this.ephemeralSoftLimit = options?.ephemeralSoftLimit ?? DC_EPHEMERAL_SOFT_LIMIT;
    this.reliableHighWaterMark = options?.reliableHighWaterMark ?? DC_RELIABLE_HIGH_WATER_MARK;
    this.reliableQueueHardLimit = options?.reliableQueueHardLimit ?? DC_RELIABLE_QUEUE_HARD_LIMIT;
    this.stallTimeoutMs = options?.stallTimeoutMs ?? DC_STALL_TIMEOUT_MS;
    this.fallbackPollMs = options?.fallbackPollMs ?? DC_FALLBACK_POLL_MS;
    this.onOverflow = options?.onOverflow;
  }

  private readonly handleBufferedAmountLow = (): void => {
    this.flush();
  };

  public attachReliableChannel(dc: RTCDataChannel): void {
    this.detachReliableChannel();
    this.reliableDc = dc;
    try {
      dc.bufferedAmountLowThreshold = this.bufferedAmountLowThreshold;
    } catch {
      // ignore in minimal mock/WebView implementations
    }
    try {
      dc.onbufferedamountlow = this.handleBufferedAmountLow;
    } catch {
      // ignore in minimal mocks
    }
    try {
      if (typeof dc.addEventListener === 'function') {
        dc.addEventListener('bufferedamountlow', this.handleBufferedAmountLow);
        this.reliableHasEventListener = true;
      }
    } catch {
      this.reliableHasEventListener = false;
    }
  }

  public detachReliableChannel(): void {
    const dc = this.reliableDc;
    if (!dc) return;
    this.reliableDc = null;
    try {
      if (dc.onbufferedamountlow === this.handleBufferedAmountLow) {
        dc.onbufferedamountlow = null;
      }
    } catch {
      // ignore
    }
    if (this.reliableHasEventListener) {
      this.reliableHasEventListener = false;
      try {
        if (typeof dc.removeEventListener === 'function') {
          dc.removeEventListener('bufferedamountlow', this.handleBufferedAmountLow);
        }
      } catch {
        // ignore
      }
    }
  }

  public attachEphemeralChannel(dc: RTCDataChannel): void {
    this.ephemeralDc = dc;
  }

  public detachEphemeralChannel(): void {
    this.ephemeralDc = null;
  }

  public hasOpenEphemeralChannel(): boolean {
    return this.ephemeralDc !== null && this.ephemeralDc.readyState === 'open';
  }

  public getQueuedBytes(): number {
    return this.queuedBytes;
  }

  public getQueuedFrameCount(): number {
    return Math.max(0, this.queue.length - this.queueHead);
  }

  public getDroppedEphemeralCount(): number {
    return this.droppedEphemeralCount;
  }

  public getTotalBufferedAmount(): number {
    const dcBuffered =
      this.reliableDc && this.reliableDc.readyState === 'open'
        ? this.reliableDc.bufferedAmount || 0
        : 0;
    return dcBuffered + this.queuedBytes;
  }

  public sendFrames(frames: readonly Uint8Array[], ephemeral: boolean = false): boolean {
    return ephemeral ? this.sendEphemeralFrames(frames) : this.sendReliableFrames(frames);
  }

  /**
   * Sends loss-tolerant low-latency frames (cursors, follow-camera).
   * Uses the unordered ephemeral channel when open (single-frame payloads), falling back
   * to the reliable channel when no ephemeral channel is available. Drops immediately
   * if the selected channel's bufferedAmount exceeds the soft threshold or reliable queue is backed up.
   */
  public sendEphemeralFrames(frames: readonly Uint8Array[]): boolean {
    if (frames.length === 0) return true;

    const eph = this.ephemeralDc;
    if (eph && eph.readyState === 'open' && frames.length === 1) {
      if ((eph.bufferedAmount || 0) > this.ephemeralSoftLimit) {
        this.droppedEphemeralCount += 1;
        return false;
      }
      try {
        eph.send(frames[0] as unknown as ArrayBuffer);
        return true;
      } catch {
        this.droppedEphemeralCount += 1;
        return false;
      }
    }

    // Fallback to reliable channel (single-channel peer or closed ephemeral channel)
    const rel = this.reliableDc;
    if (!rel || rel.readyState !== 'open') {
      this.droppedEphemeralCount += 1;
      return false;
    }
    if (this.queuedBytes > 0 || (rel.bufferedAmount || 0) > this.ephemeralSoftLimit) {
      this.droppedEphemeralCount += 1;
      return false;
    }
    try {
      for (let i = 0; i < frames.length; i++) {
        if ((rel.bufferedAmount || 0) > this.ephemeralSoftLimit) {
          this.droppedEphemeralCount += 1;
          return false;
        }
        rel.send(frames[i] as unknown as ArrayBuffer);
      }
      return true;
    } catch {
      this.droppedEphemeralCount += 1;
      return false;
    }
  }

  /**
   * Sends authoritative reliable frames in strict FIFO order.
   * Writes directly when below the high-water mark, otherwise enqueues and drains via
   * bufferedamountlow (plus a safe timer fallback) with zero silent drops.
   */
  public sendReliableFrames(frames: readonly Uint8Array[]): boolean {
    const dc = this.reliableDc;
    if (!dc || dc.readyState !== 'open') return false;
    if (frames.length === 0) return true;

    let startIdx = 0;
    if (this.queueHead >= this.queue.length) {
      while (startIdx < frames.length) {
        if ((dc.bufferedAmount || 0) >= this.reliableHighWaterMark) {
          break;
        }
        try {
          dc.send(frames[startIdx] as unknown as ArrayBuffer);
          startIdx += 1;
        } catch {
          if (dc.readyState !== 'open') return false;
          break;
        }
      }
      if (startIdx >= frames.length) {
        this.stallStartedAt = null;
        return true;
      }
    }

    let remainingBytes = 0;
    for (let i = startIdx; i < frames.length; i++) {
      remainingBytes += frames[i].byteLength;
    }

    if (this.queuedBytes + remainingBytes > this.reliableQueueHardLimit) {
      this.clear();
      this.onOverflow?.('Reliable DataChannel outbound queue exceeded safety ceiling');
      return false;
    }

    for (let i = startIdx; i < frames.length; i++) {
      this.queue.push(frames[i]);
    }
    this.queuedBytes += remainingBytes;

    if (this.stallStartedAt === null) {
      this.stallStartedAt = Date.now();
    }

    if (startIdx === 0 && (dc.bufferedAmount || 0) < this.reliableHighWaterMark) {
      this.flush();
    } else {
      this.scheduleFallbackDrain();
    }
    return true;
  }

  public flush(): void {
    const dc = this.reliableDc;
    if (!dc || dc.readyState !== 'open') {
      return;
    }

    let sentAny = false;
    while (this.queueHead < this.queue.length) {
      if ((dc.bufferedAmount || 0) >= this.reliableHighWaterMark) {
        break;
      }
      const frame = this.queue[this.queueHead];
      try {
        dc.send(frame as unknown as ArrayBuffer);
      } catch {
        if (dc.readyState !== 'open') {
          return;
        }
        break;
      }
      this.queue[this.queueHead] = undefined as unknown as Uint8Array;
      this.queueHead += 1;
      this.queuedBytes = Math.max(0, this.queuedBytes - frame.byteLength);
      sentAny = true;
    }

    if (this.queueHead >= this.queue.length) {
      this.queue.length = 0;
      this.queueHead = 0;
      this.queuedBytes = 0;
      this.stallStartedAt = null;
      this.clearDrainTimer();
      return;
    }

    if (this.queueHead >= 64 && this.queueHead * 2 >= this.queue.length) {
      this.queue = this.queue.slice(this.queueHead);
      this.queueHead = 0;
    }

    const now = Date.now();
    if (sentAny) {
      this.stallStartedAt = null;
    } else if (this.stallStartedAt === null) {
      this.stallStartedAt = now;
    } else if (now - this.stallStartedAt >= this.stallTimeoutMs) {
      this.clear();
      this.onOverflow?.('Reliable DataChannel outbound queue stalled');
      return;
    }

    this.scheduleFallbackDrain();
  }

  private scheduleFallbackDrain(): void {
    if (this.drainTimer !== null) return;
    this.drainTimer = setTimeout(() => {
      this.drainTimer = null;
      this.flush();
    }, this.fallbackPollMs);
  }

  private clearDrainTimer(): void {
    if (this.drainTimer !== null) {
      clearTimeout(this.drainTimer);
      this.drainTimer = null;
    }
  }

  public clear(): void {
    this.clearDrainTimer();
    this.queue.length = 0;
    this.queueHead = 0;
    this.queuedBytes = 0;
    this.stallStartedAt = null;
  }

  public dispose(): void {
    this.clear();
    this.detachReliableChannel();
    this.detachEphemeralChannel();
  }
}