From 39f087d7bd050d726fe1a2dc18d8e8428b2c6592 Mon Sep 17 00:00:00 2001 From: aloneangel45 Date: Sun, 22 Nov 2026 11:55:07 +0300 Subject: [PATCH 1/2] fix(signalling): forward RTP packets only to connected WebRTC peers --- .../signalling/handlers/udpSocket.test.ts | 148 ++++++++++++++++++ src/server/signalling/handlers/udpSocket.ts | 4 + 2 files changed, 152 insertions(+) create mode 100644 src/server/signalling/handlers/udpSocket.test.ts diff --git a/src/server/signalling/handlers/udpSocket.test.ts b/src/server/signalling/handlers/udpSocket.test.ts new file mode 100644 index 00000000..226ed5e4 --- /dev/null +++ b/src/server/signalling/handlers/udpSocket.test.ts @@ -0,0 +1,148 @@ +import { EventEmitter } from "node:events" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import type { ClientSession } from "./sessionStore.ts" +import { UdpSocketManager } from "./udpSocket.ts" + +const sockets = vi.hoisted(() => [] as FakeUdpSocket[]) + +class FakeUdpSocket extends EventEmitter { + bind = vi.fn((_port: number, _host: string, callback?: () => void): this => { + callback?.() + return this + }) + unref = vi.fn((): this => this) + setRecvBufferSize = vi.fn() + close = vi.fn((callback?: () => void): this => { + callback?.() + return this + }) +} + +vi.mock("node:dgram", () => { + const createSocket = vi.fn(() => { + const socket = new FakeUdpSocket() + sockets.push(socket) + return socket + }) + return { + default: { createSocket }, + createSocket, + } +}) + +vi.mock("../../../utils/logger.ts", () => ({ + default: { info: vi.fn(), error: vi.fn(), warn: vi.fn() }, +})) + +function makeSession( + sessionId: string, + connectionState: ClientSession["pc"]["connectionState"], +): ClientSession { + return { + pc: { + connectionState, + } as unknown as ClientSession["pc"], + videoTrack: { + writeRtp: vi.fn(), + } as unknown as ClientSession["videoTrack"], + audioTrack: { + writeRtp: vi.fn(), + } as unknown as ClientSession["audioTrack"], + inputHandler: { + destroy: vi.fn(), + } as unknown as ClientSession["inputHandler"], + sessionId, + bytesRecv: 0, + bytesSent: 0, + dcUnordered: { readyState: "open" } as ClientSession["dcUnordered"], + dcOrdered: { readyState: "open" } as ClientSession["dcOrdered"], + sessionSseRes: null, + pendingEvents: [], + disconnectTimer: null, + createdAt: 1_000, + } +} + +describe("UdpSocketManager RTP forwarding", () => { + let manager: UdpSocketManager | null = null + + beforeEach(() => { + sockets.length = 0 + }) + + afterEach(async () => { + if (manager) { + await manager.shutdown() + manager = null + } + vi.clearAllMocks() + }) + + it("forwards video and audio RTP only to clients with connected PeerConnections", async () => { + const connected = makeSession("connected-1", "connected") + const connecting = makeSession("connecting-1", "connecting") + const fresh = makeSession("new-1", "new") + const disconnected = makeSession("disconnected-1", "disconnected") + const failed = makeSession("failed-1", "failed") + const closed = makeSession("closed-1", "closed") + + const clients = new Map([ + [connected.sessionId, connected], + [connecting.sessionId, connecting], + [fresh.sessionId, fresh], + [disconnected.sessionId, disconnected], + [failed.sessionId, failed], + [closed.sessionId, closed], + ]) + + manager = new UdpSocketManager(clients) + await vi.waitFor(() => expect(sockets).toHaveLength(2)) + + const [videoSocket, audioSocket] = sockets + const videoPacket = Buffer.from([0x80, 0x60, 0x00, 0x01]) + const audioPacket = Buffer.from([0x80, 0xef, 0x00, 0x02, 0xaa]) + + videoSocket.emit("message", videoPacket) + audioSocket.emit("message", audioPacket) + + expect(connected.videoTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(connected.videoTrack.writeRtp).toHaveBeenCalledWith(videoPacket) + expect(connected.audioTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(connected.audioTrack.writeRtp).toHaveBeenCalledWith(audioPacket) + expect(connected.bytesSent).toBe(videoPacket.length + audioPacket.length) + + for (const nonConnected of [ + connecting, + fresh, + disconnected, + failed, + closed, + ]) { + expect(nonConnected.videoTrack.writeRtp).not.toHaveBeenCalled() + expect(nonConnected.audioTrack.writeRtp).not.toHaveBeenCalled() + expect(nonConnected.bytesSent).toBe(0) + } + }) + + it("resumes forwarding if a transiently disconnected client reconnects", async () => { + const client = makeSession("session-1", "disconnected") + const clients = new Map([[client.sessionId, client]]) + + manager = new UdpSocketManager(clients) + await vi.waitFor(() => expect(sockets).toHaveLength(2)) + + const [videoSocket] = sockets + const packet = Buffer.from([0x80, 0x60, 0x00, 0x03]) + + videoSocket.emit("message", packet) + expect(client.videoTrack.writeRtp).not.toHaveBeenCalled() + expect(client.bytesSent).toBe(0) + + Object.assign(client.pc, { connectionState: "connected" }) + videoSocket.emit("message", packet) + + expect(client.videoTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(client.videoTrack.writeRtp).toHaveBeenCalledWith(packet) + expect(client.bytesSent).toBe(packet.length) + }) +}) diff --git a/src/server/signalling/handlers/udpSocket.ts b/src/server/signalling/handlers/udpSocket.ts index e0db2a2d..bde41ae1 100644 --- a/src/server/signalling/handlers/udpSocket.ts +++ b/src/server/signalling/handlers/udpSocket.ts @@ -99,6 +99,10 @@ export class UdpSocketManager { socket.on("message", (msg) => { for (const client of this.clients.values()) { + // Skip peers until DTLS/SRTP negotiation completes and while + // disconnected/failed/closed to avoid futile writeRtp throws and + // inflated bytesSent counters. + if (client.pc.connectionState !== "connected") continue try { if (trackKind === "video") { client.videoTrack.writeRtp(msg) From d59b14b0a631febb577d5ac054fcb2163fc0dac5 Mon Sep 17 00:00:00 2001 From: aloneangel45 Date: Sun, 22 Nov 2026 12:16:56 +0300 Subject: [PATCH 2/2] fix(signalling): handle ICE recovery and narrow session type --- .../signalling/handlers/udpSocket.test.ts | 105 +++++++++--------- src/server/signalling/handlers/udpSocket.ts | 31 +++++- 2 files changed, 80 insertions(+), 56 deletions(-) diff --git a/src/server/signalling/handlers/udpSocket.test.ts b/src/server/signalling/handlers/udpSocket.test.ts index 226ed5e4..2cced53a 100644 --- a/src/server/signalling/handlers/udpSocket.test.ts +++ b/src/server/signalling/handlers/udpSocket.test.ts @@ -1,7 +1,6 @@ import { EventEmitter } from "node:events" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" -import type { ClientSession } from "./sessionStore.ts" -import { UdpSocketManager } from "./udpSocket.ts" +import { type RtpClientSession, UdpSocketManager } from "./udpSocket.ts" const sockets = vi.hoisted(() => [] as FakeUdpSocket[]) @@ -35,31 +34,21 @@ vi.mock("../../../utils/logger.ts", () => ({ })) function makeSession( - sessionId: string, - connectionState: ClientSession["pc"]["connectionState"], -): ClientSession { + connectionState: RtpClientSession["pc"]["connectionState"], + iceConnectionState: RtpClientSession["pc"]["iceConnectionState"], +): RtpClientSession { return { pc: { connectionState, - } as unknown as ClientSession["pc"], + iceConnectionState, + }, videoTrack: { writeRtp: vi.fn(), - } as unknown as ClientSession["videoTrack"], + }, audioTrack: { writeRtp: vi.fn(), - } as unknown as ClientSession["audioTrack"], - inputHandler: { - destroy: vi.fn(), - } as unknown as ClientSession["inputHandler"], - sessionId, - bytesRecv: 0, + }, bytesSent: 0, - dcUnordered: { readyState: "open" } as ClientSession["dcUnordered"], - dcOrdered: { readyState: "open" } as ClientSession["dcOrdered"], - sessionSseRes: null, - pendingEvents: [], - disconnectTimer: null, - createdAt: 1_000, } } @@ -78,21 +67,23 @@ describe("UdpSocketManager RTP forwarding", () => { vi.clearAllMocks() }) - it("forwards video and audio RTP only to clients with connected PeerConnections", async () => { - const connected = makeSession("connected-1", "connected") - const connecting = makeSession("connecting-1", "connecting") - const fresh = makeSession("new-1", "new") - const disconnected = makeSession("disconnected-1", "disconnected") - const failed = makeSession("failed-1", "failed") - const closed = makeSession("closed-1", "closed") - - const clients = new Map([ - [connected.sessionId, connected], - [connecting.sessionId, connecting], - [fresh.sessionId, fresh], - [disconnected.sessionId, disconnected], - [failed.sessionId, failed], - [closed.sessionId, closed], + it("forwards video and audio RTP only to connected peers", async () => { + const connected = makeSession("connected", "connected") + const completedIce = makeSession("connected", "completed") + const preDtlsConnecting = makeSession("connecting", "connected") + const fresh = makeSession("new", "new") + const disconnected = makeSession("disconnected", "disconnected") + const failed = makeSession("failed", "failed") + const closed = makeSession("closed", "closed") + + const clients = new Map([ + ["connected-1", connected], + ["completed-1", completedIce], + ["connecting-1", preDtlsConnecting], + ["new-1", fresh], + ["disconnected-1", disconnected], + ["failed-1", failed], + ["closed-1", closed], ]) manager = new UdpSocketManager(clients) @@ -105,44 +96,56 @@ describe("UdpSocketManager RTP forwarding", () => { videoSocket.emit("message", videoPacket) audioSocket.emit("message", audioPacket) - expect(connected.videoTrack.writeRtp).toHaveBeenCalledTimes(1) - expect(connected.videoTrack.writeRtp).toHaveBeenCalledWith(videoPacket) - expect(connected.audioTrack.writeRtp).toHaveBeenCalledTimes(1) - expect(connected.audioTrack.writeRtp).toHaveBeenCalledWith(audioPacket) - expect(connected.bytesSent).toBe(videoPacket.length + audioPacket.length) + for (const active of [connected, completedIce]) { + expect(active.videoTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(active.videoTrack.writeRtp).toHaveBeenCalledWith(videoPacket) + expect(active.audioTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(active.audioTrack.writeRtp).toHaveBeenCalledWith(audioPacket) + expect(active.bytesSent).toBe(videoPacket.length + audioPacket.length) + } - for (const nonConnected of [ - connecting, + for (const inactive of [ + preDtlsConnecting, fresh, disconnected, failed, closed, ]) { - expect(nonConnected.videoTrack.writeRtp).not.toHaveBeenCalled() - expect(nonConnected.audioTrack.writeRtp).not.toHaveBeenCalled() - expect(nonConnected.bytesSent).toBe(0) + expect(inactive.videoTrack.writeRtp).not.toHaveBeenCalled() + expect(inactive.audioTrack.writeRtp).not.toHaveBeenCalled() + expect(inactive.bytesSent).toBe(0) } }) - it("resumes forwarding if a transiently disconnected client reconnects", async () => { - const client = makeSession("session-1", "disconnected") - const clients = new Map([[client.sessionId, client]]) + it("resumes forwarding when ICE recovers from disconnected while connectionState remains disconnected", async () => { + const client = makeSession("connected", "connected") + const clients = new Map([["session-1", client]]) manager = new UdpSocketManager(clients) await vi.waitFor(() => expect(sockets).toHaveLength(2)) - const [videoSocket] = sockets + const [videoSocket, audioSocket] = sockets const packet = Buffer.from([0x80, 0x60, 0x00, 0x03]) + // Simulate ICE drop (werift sets both iceConnectionState and connectionState) + client.pc.iceConnectionState = "disconnected" + client.pc.connectionState = "disconnected" + videoSocket.emit("message", packet) + audioSocket.emit("message", packet) expect(client.videoTrack.writeRtp).not.toHaveBeenCalled() + expect(client.audioTrack.writeRtp).not.toHaveBeenCalled() expect(client.bytesSent).toBe(0) - Object.assign(client.pc, { connectionState: "connected" }) - videoSocket.emit("message", packet) + // Simulate ICE recovery (werift updates iceConnectionState without restoring connectionState) + client.pc.iceConnectionState = "connected" + videoSocket.emit("message", packet) + audioSocket.emit("message", packet) expect(client.videoTrack.writeRtp).toHaveBeenCalledTimes(1) expect(client.videoTrack.writeRtp).toHaveBeenCalledWith(packet) - expect(client.bytesSent).toBe(packet.length) + expect(client.audioTrack.writeRtp).toHaveBeenCalledTimes(1) + expect(client.audioTrack.writeRtp).toHaveBeenCalledWith(packet) + expect(client.bytesSent).toBe(packet.length * 2) }) }) diff --git a/src/server/signalling/handlers/udpSocket.ts b/src/server/signalling/handlers/udpSocket.ts index bde41ae1..2cd1d110 100644 --- a/src/server/signalling/handlers/udpSocket.ts +++ b/src/server/signalling/handlers/udpSocket.ts @@ -7,6 +7,30 @@ import type { ClientSession } from "./sessionStore.ts" // UdpSocketManager — owns the UDP sockets that receive RTP from GStreamer // --------------------------------------------------------------------------- +export interface RtpClientSession { + pc: { + connectionState: ClientSession["pc"]["connectionState"] + iceConnectionState: ClientSession["pc"]["iceConnectionState"] + } + videoTrack: Pick + audioTrack: Pick + bytesSent: number +} + +function isClientReadyForMedia(client: RtpClientSession): boolean { + const { connectionState, iceConnectionState } = client.pc + // Before initial DTLS/SRTP completion, connectionState stays "new" or + // "connecting" even once ICE connects; after a transient drop, werift sets + // connectionState to "disconnected" without restoring it when ICE recovers. + // Allow forwarding when ICE is connected/completed and the peer has moved + // past initial handshake without failing or closing. + const pastInitialHandshake = + connectionState === "connected" || connectionState === "disconnected" + const iceConnected = + iceConnectionState === "connected" || iceConnectionState === "completed" + return pastInitialHandshake && iceConnected +} + export class UdpSocketManager { private videoSocket: dgram.Socket | null = null private audioSocket: dgram.Socket | null = null @@ -17,7 +41,7 @@ export class UdpSocketManager { private rebindBackoffMs = 500 private readonly maxBackoffMs = 10_000 - constructor(private readonly clients: Map) { + constructor(private readonly clients: ReadonlyMap) { this.setup() } @@ -99,10 +123,7 @@ export class UdpSocketManager { socket.on("message", (msg) => { for (const client of this.clients.values()) { - // Skip peers until DTLS/SRTP negotiation completes and while - // disconnected/failed/closed to avoid futile writeRtp throws and - // inflated bytesSent counters. - if (client.pc.connectionState !== "connected") continue + if (!isClientReadyForMedia(client)) continue try { if (trackKind === "video") { client.videoTrack.writeRtp(msg)