chat / client / test / helpers / rtc-fakes.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
 * The slice of WebRTC that lib/media actually touches.
 *
 * Small, on purpose: `setLocalDescription`, `setRemoteDescription`,
 * `addIceCandidate`, `addTrack`, `getSenders`, `getTransceivers`, `restartIce`,
 * `close`, `getStats`, the four state properties, the four event properties, and
 * a `MediaStream` stub. That is the whole contract 445 lines of
 * perfect-negotiation logic depend on.
 *
 * Two design rules, both learned from dev/docs/CLJS.md's "a stub that silently
 * returns undefined where the browser returns data is how a fixture ends up
 * encoding the harness's bug":
 *
 *  1. The signaling state machine is REAL. `setLocalDescription()` with no
 *     argument produces an offer in "stable" and an answer in
 *     "have-remote-offer", exactly as the browser does, because the whole
 *     glare/politeness decision reads `signalingState`. A stub that left it
 *     alone would make every collision test vacuous.
 *  2. Nothing fires on its own. `onnegotiationneeded` and
 *     `onconnectionstatechange` are invoked by the scenario, never by
 *     `addTrack`, so the transcript records a sequence the script chose rather
 *     than one the double improvised.
 *
 * Every call is appended to the shared sink BEFORE any await, so a gated call
 * appears in the transcript at the moment it was made — which is what makes
 * "B never started while A was in flight" expressible.
 */

/** A deterministic track. */
export const track = (kind, id = `${kind}-1`) => ({ kind, id, stop() {} });

/** The MediaStream stub: `getTracks` is the only method lib/media calls. */
export class FakeMediaStream {
  constructor(tracks = []) {
    this._tracks = tracks;
  }
  getTracks() {
    return this._tracks.slice();
  }
}

/**
 * Install `RTCPeerConnection` and `MediaStream` on the globals, recording into
 * `sink`. Returns { created, gate, uninstall }.
 *
 *   created  every pc the code under test constructed, in order
 *   gate(m)  make method `m` ("setLocalDescription" / "setRemoteDescription" /
 *            "addIceCandidate") hang until the returned release() is called —
 *            this is how a race is held open long enough to observe
 */
export function installRtc(sink) {
  const created = [];
  const gates = new Map();

  const gate = (method) => {
    let release;
    gates.set(method, new Promise((r) => { release = r; }));
    return () => {
      gates.delete(method);
      release();
    };
  };
  const waitGate = (method) => gates.get(method) ?? null;

  // A transceiver created by addTrack has a RECEIVER TRACK from the moment it
  // exists — muted, but present and of the same kind. That is not a detail:
  // apply-media! finds an existing transceiver by `receiver.track.kind`, so a
  // stub with `receiver.track = null` makes every re-application add the track
  // AGAIN instead of reusing the transceiver, and the fixture would record a
  // double addTrack the browser never performs. (dev/docs/CLJS.md: a stub that
  // returns nothing where the browser returns data is how a fixture ends up
  // encoding the harness's bug.)
  const mkTransceiver = (kind, t) => ({
    direction: "sendrecv",
    receiver: { track: { kind, id: `${kind}-recv` } },
    sender: {
      track: t ?? null,
      kind,
      async replaceTrack(next) {
        sink.push(["pc.replaceTrack", kind, next === null ? null : next.kind]);
        this.track = next;
      },
      getParameters() {
        return { encodings: [] };
      },
      setParameters(p) {
        sink.push(["pc.setParameters", kind, p.encodings?.[0]?.maxBitrate ?? null]);
        return Promise.resolve();
      },
    },
  });

  class FakeRTCPeerConnection {
    constructor(config) {
      this.config = config;
      this.connectionState = "new";
      this.signalingState = "stable";
      this.localDescription = null;
      this.remoteDescription = null;
      this.ontrack = null;
      this.onnegotiationneeded = null;
      this.onicecandidate = null;
      this.onconnectionstatechange = null;
      this._tx = [];
      created.push(this);
      sink.push(["pc.new"]);
    }

    /** No argument = "produce the description this state calls for". */
    async setLocalDescription(desc) {
      const type = desc?.type ?? (this.signalingState === "have-remote-offer" ? "answer" : "offer");
      sink.push(["pc.setLocalDescription", type]);
      const g = waitGate("setLocalDescription");
      if (g) await g;
      this.localDescription = { type, sdp: `${type}-sdp` };
      this.signalingState = type === "offer" ? "have-local-offer" : "stable";
    }

    async setRemoteDescription(desc) {
      sink.push(["pc.setRemoteDescription", desc.type, desc.sdp]);
      const g = waitGate("setRemoteDescription");
      if (g) await g;
      this.remoteDescription = desc;
      this.signalingState = desc.type === "offer" ? "have-remote-offer" : "stable";
    }

    async addIceCandidate(candidate) {
      sink.push(["pc.addIceCandidate", candidate === undefined ? "undefined" : candidate.candidate]);
      const g = waitGate("addIceCandidate");
      if (g) await g;
    }

    /**
     * The browser THROWS InvalidAccessError when the same track is added twice,
     * and lib/media relies on that: attach-media on a fresh peer runs
     * apply-media! twice concurrently (once from setup-pc!'s tail, once off
     * peer.mediaQueue), both find no transceiver, and both call addTrack. The
     * second one throws and is swallowed by apply-media!'s own .catch. A stub
     * that quietly accepted the duplicate would record two senders the browser
     * would never have, and would hide the race entirely.
     */
    addTrack(t, _stream) {
      if (this._tx.some((tx) => tx.sender.track === t)) {
        sink.push(["pc.addTrack", t.kind, "InvalidAccessError"]);
        throw Object.assign(new Error("Track has already been added"), { name: "InvalidAccessError" });
      }
      sink.push(["pc.addTrack", t.kind]);
      const tx = mkTransceiver(t.kind, t);
      this._tx.push(tx);
      return tx.sender;
    }

    getTransceivers() {
      return this._tx.slice();
    }

    getSenders() {
      return this._tx.map((t) => t.sender);
    }

    restartIce() {
      sink.push(["pc.restartIce"]);
    }

    close() {
      sink.push(["pc.close"]);
      this.connectionState = "closed";
    }

    async getStats() {
      // an empty report: classify-transport! then reports "direct", which is
      // the deterministic branch. The stats shape itself is not under test.
      const m = new Map();
      m.forEach = Map.prototype.forEach.bind(m);
      return m;
    }

    /** Harness-side: pretend the browser moved the connection state. */
    _setConnectionState(state) {
      this.connectionState = state;
      this.onconnectionstatechange?.();
    }
  }

  const savedPc = globalThis.RTCPeerConnection;
  const savedMs = globalThis.MediaStream;
  globalThis.RTCPeerConnection = FakeRTCPeerConnection;
  globalThis.MediaStream = FakeMediaStream;

  return {
    created,
    gate,
    uninstall() {
      if (savedPc === undefined) delete globalThis.RTCPeerConnection;
      else globalThis.RTCPeerConnection = savedPc;
      if (savedMs === undefined) delete globalThis.MediaStream;
      else globalThis.MediaStream = savedMs;
    },
  };
}

/** The net double lib/media talks to: one frame handler, one send path. */
export function fakeSigNet(myId, sink) {
  const handlers = new Map();
  const sent = [];
  return {
    handlers,
    sent,
    node: {
      myId,
      handleFrames(protocol, fn) {
        handlers.set(protocol, fn);
      },
      sendFrame(protocol, to, bytes) {
        sink.push(["net.sendFrame", to, bytes.length]);
        sent.push(bytes);
        return Promise.resolve();
      },
    },
  };
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/chat.git