From 5cf7331223f89c5321769ebeb225c6be1fa075ef Mon Sep 17 00:00:00 2001 From: LainHE <36128030+LainHE@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:55:13 +0800 Subject: [PATCH] fix(webrtc): roll back the peer when the mixer codec is unavailable `WebRtcAudioSession` builds its `RTCPeerConnection`, attaches the outgoing track and adds the audio transceiver before it creates the mixer encoder. When that encoder cannot be created the constructor stops the track and throws, but it never closed the peer it had already built. The caller cannot cover for it. `handleWebRtcOffer` assigns the factory result to a local that starts as `null`: let peer: WebRtcAudioSession | null = null; ... peer = this.createWebRtcSession({ ... }); so a throwing constructor leaves `peer` at `null`, and the catch block's `if (entry.webrtc === peer) entry.webrtc = null;` and `await peer?.close()` are both no-ops. The peer was created, never closed, and no handle to it survived the unwind. The impact today is bounded, and the defect is the broken invariant rather than a measured leak: the throw lands before ICE gathering starts, before `scheduleAudioTick()` and `activityTimer` are installed, and werift's constructor binds no socket or timer of its own, so the unreachable instance is reclaimed by garbage collection. But an exception during construction must not strand a half-built resource, and any acquisition added above that point would turn this into a real leak. Close the peer before propagating the failure: * `this.peer.close()` now runs before the throw, so the peer is released even though the caller never receives the session; * `createEncoder` becomes an injectable option on `WebRtcAudioSessionOptions`, mirroring `VoiceBridgeDependencies.createEncoder` and `createWebRtcSession`. Production still resolves to `new OpusEncoder(AUDIO_SAMPLE_RATE, 1)`, so behaviour is unchanged; the seam exists so the failure branch is reachable without a machine that happens to lack the native codec. Covered by a regression test that injects a failing encoder and instruments `RTCPeerConnection.prototype.close` to count the distinct peers closed during construction. It reports 0 on the old code and 1 with the fix, in any environment and with no dependency on native Opus. --- src/server/webrtc-audio.test.ts | 28 ++++++++++++++++++++++++++++ src/server/webrtc-audio.ts | 14 ++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/server/webrtc-audio.test.ts b/src/server/webrtc-audio.test.ts index 601af2f..4e15442 100644 --- a/src/server/webrtc-audio.test.ts +++ b/src/server/webrtc-audio.test.ts @@ -173,3 +173,31 @@ test("a rejected peer shutdown is shared without repeating partial cleanup", asy assert.deepEqual(f.released, ["decoder-1", "decoder-2", "encoder", "track", "peer"]); assert.equal(f.resources.decoderByClient.size, 0); }); + +test("an unavailable mixer encoder closes the half-built peer before the constructor throws", () => { + // The constructor never returns when the codec is missing, so the caller's + // `peer?.close()` is a no-op. Instrument the prototype to observe that the + // rollback happens inside the constructor instead. Count distinct peers: + // werift re-enters close() on the same instance while tearing ICE down. + const originalClose = RTCPeerConnection.prototype.close; + const closedPeers = new Set(); + RTCPeerConnection.prototype.close = function patchedClose(this: RTCPeerConnection): Promise { + closedPeers.add(this); + return originalClose.call(this); + }; + try { + assert.throws( + () => new WebRtcAudioSession({ + connectionId: "encoder-unavailable", + logger: pino({ enabled: false }), + createEncoder: () => { throw new Error("Opus codec is unavailable"); }, + onVoiceFrame() {}, + onVoiceActivity() {}, + }), + /WebRTC Opus codec is unavailable/, + ); + } finally { + RTCPeerConnection.prototype.close = originalClose; + } + assert.equal(closedPeers.size, 1, "the constructor must roll back the peer it already created"); +}); diff --git a/src/server/webrtc-audio.ts b/src/server/webrtc-audio.ts index 70beb95..6d24c47 100644 --- a/src/server/webrtc-audio.ts +++ b/src/server/webrtc-audio.ts @@ -41,6 +41,9 @@ export interface WebRtcAudioOptions { udpPortRange?: [number, number]; } +/** The mixer only encodes; per-speaker decoders are created separately below. */ +type MixerEncoder = Pick; + export interface WebRtcAudioSessionOptions { connectionId: string; publicAddresses?: string[]; @@ -49,6 +52,8 @@ export interface WebRtcAudioSessionOptions { publicHost?: string; udpPortRange?: [number, number]; logger: LoggerType; + /** Mirrors `VoiceBridgeDependencies.createEncoder`; production uses `@discordjs/opus`. */ + createEncoder?: () => MixerEncoder; microphoneMuted?: boolean; accompanimentActive?: boolean; onVoiceFrame: (data: Buffer, codec: 4 | 5) => void; @@ -104,7 +109,7 @@ export class WebRtcAudioSession { private readonly opusPayloadTypes = new Set(); private audioTimer: ReturnType | null = null; private readonly activityTimer: ReturnType; - private encoder: OpusEncoder | null; + private encoder: MixerEncoder | null; private sequenceNumber = randomInt(0, 65_536); private timestamp = randomInt(0, 0x1_0000_0000) >>> 0; private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0; @@ -193,14 +198,19 @@ export class WebRtcAudioSession { this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track"); }); + const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1)); try { - this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1); + this.encoder = createEncoder(); } catch (error: unknown) { this.encoder = null; this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder"); } if (!this.encoder) { + // The constructor never returns, so the caller cannot clean up after us: + // its `peer` handle stays null and `peer?.close()` is a no-op. Roll the + // half-built peer back here instead of stranding it on the floor. this.outgoingTrack.stop(); + void this.peer.close().catch(() => { /* rollback is best effort */ }); throw new Error("WebRTC Opus codec is unavailable"); }