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.
This commit is contained in:
LainHE committed 2026-10-16 14:55:13 +08:00
1 parent 7715214f43
commit 5cf7331223
2 files changed
+40 -2

No files matched your search

+28
View File
@@ -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>();
RTCPeerConnection.prototype.close = function patchedClose(this: RTCPeerConnection): Promise<void> {
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");
});
+12 -2
View File
@@ -41,6 +41,9 @@ export interface WebRtcAudioOptions {
udpPortRange?: [number, number];
}
/** The mixer only encodes; per-speaker decoders are created separately below. */
type MixerEncoder = Pick<OpusEncoder, "encode" | "dispose">;
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<number>();
private audioTimer: ReturnType<typeof setTimeout> | null = null;
private readonly activityTimer: ReturnType<typeof setInterval>;
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");
}