Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rtc-remove-ffi-listener-on-server-disconnect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@livekit/rtc-node': patch
---

Stop routing FFI events to a room once the server disconnects it. A room disconnected server-side (for example deleted with `RoomServiceClient.deleteRoom`) used to keep its FFI event listener for the life of the process.
91 changes: 88 additions & 3 deletions packages/livekit-rtc/src/room.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { ConnectionState, DisconnectReason } from '@livekit/rtc-ffi-bindings';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FfiClient } from './ffi_client.js';
import {
ConnectionState,
DisconnectReason,
FfiEvent,
RoomEvent as ProtoRoomEvent,
} from '@livekit/rtc-ffi-bindings';
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';
import { FfiClient, FfiClientEvent } from './ffi_client.js';
import { Room, RoomEvent } from './room.js';

afterEach(() => vi.restoreAllMocks());
Expand Down Expand Up @@ -48,3 +53,83 @@ describe('Room.disconnect', () => {
expect(request).not.toHaveBeenCalled();
});
});

describe('FFI event listener', () => {
const roomHandle = BigInt(1);

/** A Room wired up as if connect() had succeeded, listening to FFI events. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function makeListeningRoom(): any {
const room = new Room();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const r = room as any;
// Inject a connected room without allocating native handles.
Object.assign(r, {
info: { name: 'test-room', sid: 'RM_test' },
ffiHandle: { handle: roomHandle },
localParticipant: { disposeOpenStreamWriters: vi.fn(), trackPublications: new Map() },
_connectionState: ConnectionState.CONN_CONNECTED,
});
FfiClient.instance.on(FfiClientEvent.FfiEvent, r.onFfiEvent);
onTestFinished(() => {
FfiClient.instance.removeAllListeners(FfiClientEvent.FfiEvent);
});
return r;
}

const disconnectedEvent = (reason: DisconnectReason) =>
new FfiEvent({
message: {
case: 'roomEvent',
value: new ProtoRoomEvent({
roomHandle,
message: { case: 'disconnected', value: { reason } },
}),
},
});

const registrations = (r: { onFfiEvent: unknown }) =>
FfiClient.instance.listeners(FfiClientEvent.FfiEvent).filter((l) => l === r.onFfiEvent).length;

it('is removed when the server disconnects the room', async () => {
const r = makeListeningRoom();
const disconnected = vi.fn();
r.on(RoomEvent.Disconnected, disconnected);

await r.onFfiEvent(disconnectedEvent(DisconnectReason.ROOM_DELETED));

expect(disconnected).toHaveBeenCalledExactlyOnceWith(DisconnectReason.ROOM_DELETED);
expect(r.connectionState).toBe(ConnectionState.CONN_DISCONNECTED);
expect(registrations(r)).toBe(0);
});

it('is removed by disconnect()', async () => {
const r = makeListeningRoom();
vi.spyOn(FfiClient.instance, 'request').mockReturnValue({ asyncId: BigInt(1) });
vi.spyOn(FfiClient.instance, 'waitFor').mockResolvedValue({ asyncId: BigInt(1) });

await r.disconnect();

expect(registrations(r)).toBe(0);
});

it('is kept for a connect() started from RoomEvent.Disconnected during disconnect()', async () => {
const r = makeListeningRoom();
vi.spyOn(FfiClient.instance, 'request').mockReturnValue({ asyncId: BigInt(1) });
vi.spyOn(FfiClient.instance, 'waitFor')
// disconnect(): the room event arrives before the disconnect callback.
.mockImplementationOnce(async () => {
await r.onFfiEvent(disconnectedEvent(DisconnectReason.CLIENT_INITIATED));
return { asyncId: BigInt(1) };
})
// connect(): the join is still in progress when disconnect() returns.
.mockReturnValueOnce(new Promise(() => {}));
r.once(RoomEvent.Disconnected, () => {
void r.connect('ws://localhost:7880', 'token');
});

await r.disconnect();

expect(registrations(r)).toBe(1);
});
});
9 changes: 8 additions & 1 deletion packages/livekit-rtc/src/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,6 @@ export class Room extends (EventEmitter as new () => TypedEmitter<RoomCallbacks>
});

this.cleanupOnDisconnect(reason);
FfiClient.instance.removeListener(FfiClientEvent.FfiEvent, this.onFfiEvent);

this.removeAllListeners();
}
Expand Down Expand Up @@ -515,6 +514,14 @@ export class Room extends (EventEmitter as new () => TypedEmitter<RoomCallbacks>
// to reject and clean up their event listeners.
this.disconnectController.abort();

// Stop routing FFI events to this room, whichever path disconnected it:
// disconnect() returns early once the server has disconnected the room, and
// a listener left behind receives every later FFI event of the process and
// keeps the Room from being garbage collected. This runs before
// RoomEvent.Disconnected, so a connect() started from that event keeps the
// listener it registers.
FfiClient.instance.off(FfiClientEvent.FfiEvent, this.onFfiEvent);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

this.updateConnectionState(ConnectionState.CONN_DISCONNECTED);
this.emit(RoomEvent.Disconnected, reason);
}
Expand Down
Loading