Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(voice): clean up stale call participants (#3874)

Hampus643c5c2489c6
diff --git a/fluxer_api/src/api/Config.ts b/fluxer_api/src/api/Config.ts
index 485cdc28b..5072fbee5 100644
--- a/fluxer_api/src/api/Config.ts
+++ b/fluxer_api/src/api/Config.ts
@@ -503,6 +503,8 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
turnServers: master.integrations.voice.turn_servers ?? [],
joinAllowPrivateEndpoints: master.integrations.voice.join_allow_private_endpoints ?? false,
healthIntervalMs: master.integrations.voice.health_interval_ms ?? 15000,
+ participantSweepEnabled: master.integrations.voice.participant_sweep_enabled ?? true,
+ participantSweepDryRun: master.integrations.voice.participant_sweep_dry_run ?? true,
},
stripe: {
enabled: master.integrations.stripe.enabled,
diff --git a/fluxer_api/src/api/config/APIConfig.ts b/fluxer_api/src/api/config/APIConfig.ts
index de7181cdf..9666d973c 100644
--- a/fluxer_api/src/api/config/APIConfig.ts
+++ b/fluxer_api/src/api/config/APIConfig.ts
@@ -232,6 +232,8 @@ export interface APIConfig {
turnServers: Array<VoiceTurnServerConfig>;
joinAllowPrivateEndpoints: boolean;
healthIntervalMs: number;
+ participantSweepEnabled: boolean;
+ participantSweepDryRun: boolean;
};
stripe: {
enabled: boolean;
diff --git a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
index 304d16586..ac3d20aab 100644
--- a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
@@ -1,6 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {ILiveKitService, ListParticipantsResult} from '@app/api/infrastructure/ILiveKitService';
+import type {
+ GetParticipantResult,
+ ILiveKitService,
+ ListParticipantsResult,
+ ListRoomsResult,
+} from '@app/api/infrastructure/ILiveKitService';
import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';
export class DisabledLiveKitService implements ILiveKitService {
@@ -19,10 +24,26 @@ export class DisabledLiveKitService implements ILiveKitService {
async disconnectParticipant(): Promise<void> {}
+ async removeParticipant(): Promise<void> {}
+
+ async getParticipant(): Promise<GetParticipantResult> {
+ return {status: 'ok', participant: null};
+ }
+
+ async setParticipantPermission(): Promise<void> {}
+
+ async listRooms(): Promise<ListRoomsResult> {
+ return {status: 'ok', rooms: []};
+ }
+
async listParticipants(): Promise<ListParticipantsResult> {
return {status: 'ok', participants: []};
}
+ listServers(): Array<{regionId: string; serverId: string}> {
+ return [];
+ }
+
getDefaultRegionId(): string | null {
return null;
}
diff --git a/fluxer_api/src/api/infrastructure/ILiveKitService.ts b/fluxer_api/src/api/infrastructure/ILiveKitService.ts
index 094c58f7f..781ea6ed9 100644
--- a/fluxer_api/src/api/infrastructure/ILiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/ILiveKitService.ts
@@ -2,6 +2,7 @@
import type {ChannelID, GuildID, UserID} from '@app/api/BrandedTypes';
import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';
+import type {ParticipantPermission} from 'livekit-server-sdk';
export interface CreateTokenParams {
userId: UserID;
@@ -64,6 +65,35 @@ export interface DisconnectParticipantParams {
serverId: string;
}
+export interface LiveKitParticipantRef {
+ regionId: string;
+ serverId: string;
+ roomName: string;
+ identity: string;
+}
+
+export interface ListRoomsParams {
+ regionId: string;
+ serverId: string;
+}
+
+interface ListRoomsSuccess {
+ status: 'ok';
+ rooms: Array<{
+ name: string;
+ numParticipants: number;
+ }>;
+}
+
+interface LiveKitLookupError {
+ status: 'error';
+ errorCode: string;
+ retryable: boolean;
+ serverMissing?: boolean;
+}
+
+export type ListRoomsResult = ListRoomsSuccess | LiveKitLookupError;
+
export interface ListParticipantsParams {
guildId?: GuildID;
channelId: ChannelID;
@@ -75,17 +105,26 @@ interface ListParticipantsSuccess {
status: 'ok';
participants: Array<{
identity: string;
+ joinedAt: number;
+ metadata: string;
}>;
}
-interface ListParticipantsError {
- status: 'error';
- errorCode: string;
- retryable: boolean;
- serverMissing?: boolean;
+export type ListParticipantsResult = ListParticipantsSuccess | LiveKitLookupError;
+
+export interface SetParticipantPermissionParams extends LiveKitParticipantRef {
+ permission: Partial<ParticipantPermission>;
+}
+
+interface GetParticipantSuccess {
+ status: 'ok';
+ participant: {
+ joinedAt: number;
+ metadata: string;
+ } | null;
}
-export type ListParticipantsResult = ListParticipantsSuccess | ListParticipantsError;
+export type GetParticipantResult = GetParticipantSuccess | LiveKitLookupError;
export abstract class ILiveKitService {
abstract createToken(params: CreateTokenParams): Promise<{
@@ -101,8 +140,16 @@ export abstract class ILiveKitService {
abstract disconnectParticipant(params: DisconnectParticipantParams): Promise<void>;
+ abstract removeParticipant(params: LiveKitParticipantRef): Promise<void>;
+ abstract getParticipant(params: LiveKitParticipantRef): Promise<GetParticipantResult>;
+ abstract setParticipantPermission(params: SetParticipantPermissionParams): Promise<void>;
+
+ abstract listRooms(params: ListRoomsParams): Promise<ListRoomsResult>;
+
abstract listParticipants(params: ListParticipantsParams): Promise<ListParticipantsResult>;
+ abstract listServers(): Array<{regionId: string; serverId: string}>;
+
abstract getDefaultRegionId(): string | null;
abstract getRegionMetadata(): Array<VoiceRegionMetadata>;
diff --git a/fluxer_api/src/api/infrastructure/LiveKitService.ts b/fluxer_api/src/api/infrastructure/LiveKitService.ts
index 4ce9c76a0..4e1cade92 100644
--- a/fluxer_api/src/api/infrastructure/LiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/LiveKitService.ts
@@ -5,10 +5,15 @@ import {Config} from '@app/api/Config';
import {
type CreateTokenParams,
type DisconnectParticipantParams,
+ type GetParticipantResult,
ILiveKitService,
type ListParticipantsParams,
type ListParticipantsResult,
+ type ListRoomsParams,
+ type ListRoomsResult,
+ type LiveKitParticipantRef,
type MuteMicrophoneTrackParams,
+ type SetParticipantPermissionParams,
type UpdateParticipantParams,
type UpdateParticipantPermissionsParams,
} from '@app/api/infrastructure/ILiveKitService';
@@ -243,27 +248,93 @@ export class LiveKitService extends ILiveKitService {
async disconnectParticipant(params: DisconnectParticipantParams): Promise<void> {
const {userId, guildId, channelId, connectionId, regionId, serverId} = params;
- const roomName = this.getRoomName(guildId, channelId);
- const participantIdentity = this.getParticipantIdentity(userId, connectionId);
+ await this.removeParticipant({
+ regionId,
+ serverId,
+ roomName: this.getRoomName(guildId, channelId),
+ identity: this.getParticipantIdentity(userId, connectionId),
+ });
+ }
+
+ async removeParticipant(params: LiveKitParticipantRef): Promise<void> {
+ const {regionId, serverId, roomName, identity} = params;
const server = this.tryResolveServerClient(regionId, serverId);
if (server === null) {
Logger.debug(
- {regionId, serverId, participantIdentity, roomName},
+ {regionId, serverId, participantIdentity: identity, roomName},
'LiveKit disconnect skipped — pinned server no longer exists in topology',
);
return;
}
try {
- await server.roomServiceClient.removeParticipant(roomName, participantIdentity);
+ await server.roomServiceClient.removeParticipant(roomName, identity);
} catch (error) {
if (LiveKitService.isHttp404(error)) {
- Logger.debug({participantIdentity, roomName}, 'LiveKit participant already disconnected');
+ Logger.debug({participantIdentity: identity, roomName}, 'LiveKit participant already disconnected');
return;
}
Logger.error({error}, 'Error disconnecting LiveKit participant');
}
}
+ async getParticipant(params: LiveKitParticipantRef): Promise<GetParticipantResult> {
+ const {regionId, serverId, roomName, identity} = params;
+ const server = this.tryResolveServerClient(regionId, serverId);
+ if (server === null) {
+ return {status: 'error', errorCode: 'server_missing', retryable: false, serverMissing: true};
+ }
+ try {
+ const participant = await server.roomServiceClient.getParticipant(roomName, identity);
+ return {
+ status: 'ok',
+ participant: {joinedAt: Number(participant.joinedAt), metadata: participant.metadata},
+ };
+ } catch (error) {
+ if (LiveKitService.isHttp404(error)) {
+ return {status: 'ok', participant: null};
+ }
+ Logger.warn(
+ {error, regionId, serverId, roomName, participantIdentity: identity},
+ 'LiveKit getParticipant failed',
+ );
+ return LiveKitService.lookupError(error);
+ }
+ }
+
+ async setParticipantPermission(params: SetParticipantPermissionParams): Promise<void> {
+ const {regionId, serverId, roomName, identity, permission} = params;
+ const server = this.tryResolveServerClient(regionId, serverId);
+ if (server === null) {
+ return;
+ }
+ try {
+ await server.roomServiceClient.updateParticipant(roomName, identity, undefined, permission);
+ } catch (error) {
+ if (LiveKitService.isHttp404(error)) {
+ return;
+ }
+ Logger.error({error, participantIdentity: identity, roomName}, 'Error updating LiveKit participant permission');
+ }
+ }
+
+ async listRooms(params: ListRoomsParams): Promise<ListRoomsResult> {
+ const {regionId, serverId} = params;
+ const server = this.tryResolveServerClient(regionId, serverId);
+ if (server === null) {
+ return {status: 'error', errorCode: 'server_missing', retryable: false, serverMissing: true};
+ }
+ try {
+ const rooms = await server.roomServiceClient.listRooms();
+ return {
+ status: 'ok',
+ rooms: rooms.map((room) => ({name: room.name, numParticipants: room.numParticipants})),
+ };
+ } catch (error) {
+ Logger.warn({error, regionId, serverId}, 'LiveKit listRooms failed');
+ return LiveKitService.lookupError(error);
+ }
+ }
+
async listParticipants(params: ListParticipantsParams): Promise<ListParticipantsResult> {
const {guildId, channelId, regionId, serverId} = params;
const roomName = this.getRoomName(guildId, channelId);
@@ -280,20 +351,27 @@ export class LiveKitService extends ILiveKitService {
const participants = await server.roomServiceClient.listParticipants(roomName);
return {
status: 'ok',
- participants: participants.map((participant) => ({identity: participant.identity})),
+ participants: participants.map((participant) => ({
+ identity: participant.identity,
+ joinedAt: Number(participant.joinedAt),
+ metadata: participant.metadata,
+ })),
};
} catch (error) {
Logger.warn({error, regionId, serverId, roomName}, 'LiveKit listParticipants failed');
- const status = LiveKitService.getHttpStatus(error);
- const isRetryable = status != null && status >= 500;
- return {
- status: 'error',
- errorCode: error instanceof Error ? error.message : 'unknown',
- retryable: isRetryable,
- };
+ return LiveKitService.lookupError(error);
}
}
+ private static lookupError(error: unknown): {status: 'error'; errorCode: string; retryable: boolean} {
+ const status = LiveKitService.getHttpStatus(error);
+ return {
+ status: 'error',
+ errorCode: error instanceof Error ? error.message : 'unknown',
+ retryable: status != null && status >= 500,
+ };
+ }
+
private static isHttp404(error: unknown): boolean {
return LiveKitService.getHttpStatus(error) === 404;
}
@@ -314,6 +392,16 @@ export class LiveKitService extends ILiveKitService {
return this.serverClients.get(regionId)?.get(serverId) ?? null;
}
+ listServers(): Array<{regionId: string; serverId: string}> {
+ const servers: Array<{regionId: string; serverId: string}> = [];
+ for (const [regionId, regionServers] of this.serverClients) {
+ for (const serverId of regionServers.keys()) {
+ servers.push({regionId, serverId});
+ }
+ }
+ return servers;
+ }
+
getDefaultRegionId(): string | null {
return this.topology.getDefaultRegionId();
}
diff --git a/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts b/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
index a8c192b06..c15712044 100644
--- a/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
+++ b/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
@@ -2,13 +2,18 @@
import type {ChannelID, GuildID} from '@app/api/BrandedTypes';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
+import type {ILiveKitService, LiveKitParticipantRef} from '@app/api/infrastructure/ILiveKitService';
import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
import {SERVER_MUTE_ATTRIBUTE} from '@app/api/infrastructure/LiveKitService';
import {isDMRoom, parseParticipantMetadataWithRaw, parseRoomName} from '@app/api/infrastructure/VoiceRoomContext';
import {Logger} from '@app/api/Logger';
+import {
+ voiceParticipantConfirmUnavailableTotal,
+ voiceParticipantsDisconnectedTotal,
+} from '@app/api/voice/VoiceParticipantMetrics';
import type {VoiceTopology} from '@app/api/voice/VoiceTopology';
-import type {WebhookEvent} from 'livekit-server-sdk';
+import {ms} from 'itty-time';
+import type {ParticipantPermission, WebhookEvent} from 'livekit-server-sdk';
import {TrackSource, WebhookReceiver} from 'livekit-server-sdk';
const WEBHOOK_CLOCK_TOLERANCE_SECONDS = 60;
@@ -26,6 +31,22 @@ interface VoiceWebhookParticipantContext {
readonly guildId?: GuildID;
}
+type ParticipantContext = NonNullable<ReturnType<typeof parseParticipantMetadataWithRaw>>['context'];
+
+type ConfirmOutcome =
+ | {status: 'confirmed'}
+ | {status: 'rejected'; error: string | undefined}
+ | {status: 'unavailable'; error: unknown};
+
+const CONFIRM_ATTEMPTS = 2;
+const DM_CONFIRM_RECHECK_DELAYS_MS = [ms('5 seconds'), ms('10 seconds')];
+
+function sleep(durationMs: number): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, durationMs);
+ });
+}
+
export class LiveKitWebhookService {
private receivers: Map<string, WebhookReceiver>;
private serversByKey: Map<string, Array<SourceServer>>;
@@ -207,101 +228,152 @@ export class LiveKitWebhookService {
}
private async handleParticipantJoined(event: WebhookEvent, apiKey: string): Promise<void> {
- if (event.event !== 'participant_joined') {
+ if (event.event !== 'participant_joined' || !event.participant) {
return;
}
const {participant} = event;
- if (!participant?.metadata) {
- Logger.debug('Participant joined without metadata, skipping');
- return;
- }
- const parsed = parseParticipantMetadataWithRaw(participant.metadata);
+ const roomName = event.room?.name ?? null;
+ const metadata = participant.metadata ?? '';
+ const parsed = metadata ? parseParticipantMetadataWithRaw(metadata) : null;
if (!parsed) {
- Logger.warn({metadata: participant.metadata}, 'Failed to parse participant metadata');
+ Logger.warn(
+ {participantIdentity: participant.identity, roomName, hasMetadata: Boolean(metadata)},
+ 'LiveKit participant_joined without usable metadata - disconnecting participant',
+ );
+ await this.removeJoinedParticipant(
+ await this.locateJoinedParticipant({apiKey, roomName, identity: participant.identity, metadata}),
+ 'unidentified',
+ );
return;
}
const {context, raw} = parsed;
- const tokenNonce = raw.token_nonce;
- const source = this.resolveSource(apiKey, raw);
- if (
- !source ||
- !(await this.isFromPinnedServer(
- context.type === 'guild' ? context.guildId : undefined,
- context.channelId,
- source,
- ))
- ) {
+ const outcome = await this.confirmWithRetry(context, raw.token_nonce);
+ const logContext = {
+ type: context.type,
+ guildId: context.type === 'guild' ? context.guildId.toString() : undefined,
+ channelId: context.channelId.toString(),
+ connectionId: context.connectionId,
+ participantIdentity: participant.identity,
+ roomName,
+ };
+ if (outcome.status === 'confirmed') {
return;
}
- Logger.debug(
- {
- type: context.type,
- participantIdentity: participant.identity,
- roomName: event.room?.name ?? null,
- channelId: context.channelId.toString(),
- guildId: context.type === 'guild' ? context.guildId.toString() : undefined,
- connectionId: context.connectionId,
- tokenNonce,
- },
- 'Processing LiveKit participant_joined event',
+ if (outcome.status === 'unavailable') {
+ voiceParticipantConfirmUnavailableTotal.inc();
+ Logger.warn(
+ {...logContext, error: outcome.error},
+ 'LiveKit participant_joined confirm unavailable - leaving participant for the sweep',
+ );
+ return;
+ }
+ const located = await this.locateJoinedParticipant({apiKey, roomName, identity: participant.identity, metadata});
+ if (context.type === 'dm' && participant.permission) {
+ void this.holdDmJoin(context, raw.token_nonce, located, participant.permission, logContext);
+ return;
+ }
+ Logger.warn(
+ {...logContext, error: outcome.error},
+ 'LiveKit participant_joined rejected - disconnecting participant',
);
+ await this.removeJoinedParticipant(located, 'rejected');
+ }
+
+ private async holdDmJoin(
+ context: ParticipantContext,
+ tokenNonce: string,
+ located: Array<LiveKitParticipantRef>,
+ permission: ParticipantPermission,
+ logContext: Record<string, unknown>,
+ ): Promise<void> {
+ const setPermission = async (next: Partial<ParticipantPermission>) => {
+ for (const ref of located) {
+ await this.liveKitService.setParticipantPermission({...ref, permission: next});
+ }
+ };
try {
- const guildId = context.type === 'guild' ? context.guildId : undefined;
- Logger.debug(
- {
- type: context.type,
- guildId: guildId?.toString(),
- channelId: context.channelId.toString(),
- connectionId: context.connectionId,
- participantIdentity: participant.identity,
- },
- 'LiveKit participant_joined - confirming voice connection',
+ await setPermission({...permission, canSubscribe: false});
+ let outcome: ConfirmOutcome = {status: 'rejected', error: undefined};
+ for (const delayMs of DM_CONFIRM_RECHECK_DELAYS_MS) {
+ await sleep(delayMs);
+ outcome = await this.confirmWithRetry(context, tokenNonce);
+ if (outcome.status !== 'rejected') {
+ await setPermission(permission);
+ return;
+ }
+ }
+ Logger.warn(
+ {...logContext, error: outcome.status === 'rejected' ? outcome.error : undefined},
+ 'LiveKit participant_joined rejected - disconnecting participant',
);
- const result = await this.gatewayService.confirmVoiceConnection({
- guildId,
- channelId: context.channelId,
- connectionId: context.connectionId,
- tokenNonce,
- });
- Logger.debug(
- {
- type: context.type,
- guildId: guildId?.toString(),
- channelId: context.channelId.toString(),
+ await this.removeJoinedParticipant(located, 'rejected');
+ } catch (error) {
+ Logger.error({...logContext, error}, 'Failed to recheck LiveKit call participant');
+ }
+ }
+
+ private async confirmWithRetry(context: ParticipantContext, tokenNonce: string): Promise<ConfirmOutcome> {
+ let lastError: unknown = null;
+ for (let attempt = 0; attempt < CONFIRM_ATTEMPTS; attempt += 1) {
+ try {
+ const result = await this.gatewayService.confirmVoiceConnection({
+ guildId: context.type === 'guild' ? context.guildId : undefined,
+ channelId: context.channelId,
connectionId: context.connectionId,
- success: result.success,
- error: result.error,
- },
- 'LiveKit voice connection confirm result',
+ tokenNonce,
+ });
+ return result.success ? {status: 'confirmed'} : {status: 'rejected', error: result.error};
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ return {status: 'unavailable', error: lastError};
+ }
+
+ private async locateJoinedParticipant(params: {
+ apiKey: string;
+ roomName: string | null;
+ identity: string;
+ metadata: string;
+ }): Promise<Array<LiveKitParticipantRef>> {
+ const {apiKey, roomName, identity, metadata} = params;
+ const servers = this.serversByKey.get(apiKey) ?? [];
+ if (roomName === null || servers.length === 0) {
+ Logger.warn(
+ {participantIdentity: identity, roomName, serverCount: servers.length},
+ 'Cannot determine where to disconnect LiveKit participant',
);
- if (!result.success) {
- Logger.warn(
- {
- type: context.type,
- guildId: guildId?.toString(),
- channelId: context.channelId.toString(),
- connectionId: context.connectionId,
- error: result.error,
- participantIdentity: participant.identity,
- },
- 'LiveKit participant_joined rejected - disconnecting participant',
- );
- try {
- await this.liveKitService.disconnectParticipant({
- guildId,
- channelId: context.channelId,
- userId: context.userId,
- connectionId: context.connectionId,
- regionId: source.regionId,
- serverId: source.serverId,
- });
- } catch (disconnectError) {
- Logger.error({error: disconnectError}, 'Failed to disconnect rejected participant');
- }
- return;
+ return [];
+ }
+ const refs = servers.map((server) => ({
+ regionId: server.regionId,
+ serverId: server.serverId,
+ roomName,
+ identity,
+ }));
+ if (refs.length === 1) {
+ return refs;
+ }
+ const located: Array<LiveKitParticipantRef> = [];
+ for (const ref of refs) {
+ const result = await this.liveKitService.getParticipant(ref);
+ if (result.status === 'ok' && result.participant?.metadata === metadata) {
+ located.push(ref);
}
- } catch (error) {
- Logger.error({error, type: context.type}, 'Error processing participant_joined');
+ }
+ return located;
+ }
+
+ private async removeJoinedParticipant(
+ located: Array<LiveKitParticipantRef>,
+ reason: 'unidentified' | 'rejected',
+ ): Promise<void> {
+ if (located.length === 0) {
+ return;
+ }
+ voiceParticipantsDisconnectedTotal.inc(`reason="${reason}"`);
+ for (const ref of located) {
+ await this.liveKitService.removeParticipant(ref);
}
}
diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookParticipantJoined.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookParticipantJoined.test.ts
new file mode 100644
index 000000000..a6ccd6a68
--- /dev/null
+++ b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookParticipantJoined.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
+import type {ILiveKitService, LiveKitParticipantRef} from '@app/api/infrastructure/ILiveKitService';
+import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
+import {LiveKitWebhookService} from '@app/api/infrastructure/LiveKitWebhookService';
+import type {VoiceTopology} from '@app/api/voice/VoiceTopology';
+import type {WebhookEvent} from 'livekit-server-sdk';
+import {describe, expect, it} from 'vitest';
+
+const ROOM = 'guild_10_channel_20';
+const IDENTITY = 'user_1_conn-1';
+const METADATA = JSON.stringify({
+ user_id: '1',
+ channel_id: '20',
+ guild_id: '10',
+ connection_id: 'conn-1',
+ token_nonce: 'nonce-1',
+ issued_at: '1',
+ region_id: 'eu',
+ server_id: 'eu-1',
+});
+
+function createService(confirm: () => Promise<{success: boolean; error?: string}>) {
+ const removed: Array<LiveKitParticipantRef> = [];
+ let confirmCalls = 0;
+ const topology = {
+ registerSubscriber: () => {},
+ getAllRegions: () => [{id: 'eu'}],
+ getServersForRegion: () => [{serverId: 'eu-1', apiKey: 'key', apiSecret: 'secret'}],
+ } as unknown as VoiceTopology;
+ const gatewayService = {
+ confirmVoiceConnection: async () => {
+ confirmCalls += 1;
+ return confirm();
+ },
+ } as unknown as IGatewayService;
+ const liveKitService = {
+ removeParticipant: async (params: LiveKitParticipantRef) => {
+ removed.push(params);
+ },
+ } as unknown as ILiveKitService;
+ const service = new LiveKitWebhookService({} as IVoiceRoomStore, gatewayService, liveKitService, topology);
+ const join = (metadata: string) =>
+ service.processEvent({
+ apiKey: 'key',
+ event: {
+ event: 'participant_joined',
+ room: {name: ROOM},
+ participant: {identity: IDENTITY, metadata},
+ } as unknown as WebhookEvent,
+ });
+ return {join, removed, confirmCalls: () => confirmCalls};
+}
+
+describe('LiveKitWebhookService participant_joined', () => {
+ it('disconnects a participant whose metadata cannot be read', async () => {
+ const harness = createService(async () => ({success: true}));
+ await harness.join('');
+ await harness.join('{"user_id":"1"}');
+ expect(harness.removed).toEqual([
+ {regionId: 'eu', serverId: 'eu-1', roomName: ROOM, identity: IDENTITY},
+ {regionId: 'eu', serverId: 'eu-1', roomName: ROOM, identity: IDENTITY},
+ ]);
+ expect(harness.confirmCalls()).toBe(0);
+ });
+
+ it('disconnects a participant the gateway rejects', async () => {
+ const harness = createService(async () => ({success: false, error: 'voice_nonce_mismatch'}));
+ await harness.join(METADATA);
+ expect(harness.removed).toEqual([{regionId: 'eu', serverId: 'eu-1', roomName: ROOM, identity: IDENTITY}]);
+ });
+});
diff --git a/fluxer_api/src/api/voice/VoiceParticipantMetrics.ts b/fluxer_api/src/api/voice/VoiceParticipantMetrics.ts
new file mode 100644
index 000000000..8eb112b9a
--- /dev/null
+++ b/fluxer_api/src/api/voice/VoiceParticipantMetrics.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {registerCounter} from '@fluxer/hono/src/middleware/Metrics';
+
+export const voiceParticipantsDisconnectedTotal = registerCounter(
+ 'fluxer_api_voice_participants_disconnected_total',
+ 'LiveKit participants removed because they had no matching voice state, by reason',
+);
+export const voiceParticipantConfirmUnavailableTotal = registerCounter(
+ 'fluxer_api_voice_participant_confirm_unavailable_total',
+ 'LiveKit participant joins left in place because the gateway confirm did not answer',
+);
+export const voiceParticipantSweepCandidatesTotal = registerCounter(
+ 'fluxer_api_voice_participant_sweep_candidates_total',
+ 'LiveKit participants seen without a matching voice state during a sweep',
+);
diff --git a/fluxer_api/src/api/voice/VoiceParticipantSweep.ts b/fluxer_api/src/api/voice/VoiceParticipantSweep.ts
new file mode 100644
index 000000000..679221ce2
--- /dev/null
+++ b/fluxer_api/src/api/voice/VoiceParticipantSweep.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
+import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
+import {REXCTL_TEST_ROOM_PREFIX} from '@app/api/infrastructure/LiveKitWebhookService';
+import {isDMRoom, parseParticipantMetadataWithRaw, parseRoomName} from '@app/api/infrastructure/VoiceRoomContext';
+import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
+import {
+ voiceParticipantSweepCandidatesTotal,
+ voiceParticipantsDisconnectedTotal,
+} from '@app/api/voice/VoiceParticipantMetrics';
+import {UnknownChannelError} from '@fluxer/errors/src/domains/channel/UnknownChannelError';
+import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
+import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
+import {ms} from 'itty-time';
+
+const VOICE_PARTICIPANT_SETTLE_MS = ms('2 minutes');
+const MAX_VOICE_PARTICIPANT_REMOVALS_PER_SWEEP = 25;
+const SERVER_CONCURRENCY = 2;
+const ROOM_CONCURRENCY = 8;
+const IDENTITY_PATTERN = /^user_(\d+)_(.+)$/;
+
+interface VoiceParticipantSighting {
+ joinedAt: number;
+ firstSeenAt: number;
+}
+
+export type VoiceParticipantSightings = Record<string, VoiceParticipantSighting>;
+
+export interface VoiceParticipantSweepDeps {
+ liveKitService: Pick<
+ ILiveKitService,
+ 'listServers' | 'listRooms' | 'listParticipants' | 'getParticipant' | 'removeParticipant'
+ >;
+ gatewayService: Pick<IGatewayService, 'getVoiceStatesForChannel'>;
+ logger: LoggerInterface;
+ now: () => number;
+ dryRun: boolean;
+}
+
+interface VoiceParticipantSweepResult {
+ sightings: VoiceParticipantSightings;
+ rooms: number;
+ skippedRooms: number;
+ candidates: number;
+ removed: number;
+ deferred: number;
+}
+
+type RoomContext = NonNullable<ReturnType<typeof parseRoomName>>;
+
+interface SweepRoom {
+ regionId: string;
+ serverId: string;
+ roomName: string;
+ context: RoomContext;
+}
+
+interface DueParticipant {
+ key: string;
+ room: SweepRoom;
+ identity: string;
+ gatewayKey: string | null;
+ joinedAt: number;
+ firstSeenAt: number;
+}
+
+export async function sweepVoiceParticipants(
+ deps: VoiceParticipantSweepDeps,
+ previous: VoiceParticipantSightings,
+): Promise<VoiceParticipantSweepResult> {
+ const rooms = await listSweepRooms(deps);
+ const sightings: VoiceParticipantSightings = {};
+ const due: Array<DueParticipant> = [];
+ let skippedRooms = 0;
+ await mapWithConcurrency(rooms, ROOM_CONCURRENCY, async (room) => {
+ const checked = await checkRoom(deps, room, previous, sightings, due);
+ if (!checked) skippedRooms += 1;
+ });
+ const candidates = Object.keys(sightings).length;
+ voiceParticipantSweepCandidatesTotal.inc('', candidates);
+ due.sort((a, b) => a.firstSeenAt - b.firstSeenAt);
+ const removable = due.slice(0, MAX_VOICE_PARTICIPANT_REMOVALS_PER_SWEEP);
+ let removed = 0;
+ for (const participant of removable) {
+ const outcome = await removeIfStillMissing(deps, participant);
+ if (outcome !== 'unknown') {
+ delete sightings[participant.key];
+ }
+ if (outcome === 'removed') {
+ removed += 1;
+ }
+ }
+ return {
+ sightings,
+ rooms: rooms.length,
+ skippedRooms,
+ candidates,
+ removed,
+ deferred: due.length - removable.length,
+ };
+}
+
+async function listSweepRooms(deps: VoiceParticipantSweepDeps): Promise<Array<SweepRoom>> {
+ const perServer = await mapWithConcurrency(deps.liveKitService.listServers(), SERVER_CONCURRENCY, async (server) => {
+ const result = await deps.liveKitService.listRooms(server);
+ if (result.status === 'error') {
+ deps.logger.warn({...server, errorCode: result.errorCode}, 'Voice participant sweep could not list rooms');
+ return [];
+ }
+ const rooms: Array<SweepRoom> = [];
+ for (const room of result.rooms) {
+ const context = parseRoomName(room.name);
+ if (room.numParticipants === 0 || room.name.startsWith(REXCTL_TEST_ROOM_PREFIX) || context === null) {
+ continue;
+ }
+ rooms.push({...server, roomName: room.name, context});
+ }
+ return rooms;
+ });
+ return perServer.flat();
+}
+
+async function checkRoom(
+ deps: VoiceParticipantSweepDeps,
+ room: SweepRoom,
+ previous: VoiceParticipantSightings,
+ sightings: VoiceParticipantSightings,
+ due: Array<DueParticipant>,
+): Promise<boolean> {
+ const listed = await deps.liveKitService.listParticipants({
+ guildId: isDMRoom(room.context) ? undefined : room.context.guildId,
+ channelId: room.context.channelId,
+ regionId: room.regionId,
+ serverId: room.serverId,
+ });
+ if (listed.status === 'error' || listed.participants.length === 0) {
+ return listed.status === 'ok';
+ }
+ const known = await gatewayParticipantKeys(deps, room);
+ if (known === null) {
+ return false;
+ }
+ const now = deps.now();
+ for (const participant of listed.participants) {
+ const gatewayKey = participantGatewayKey(participant.identity, participant.metadata);
+ if (gatewayKey !== null && known.has(gatewayKey)) {
+ continue;
+ }
+ const key = `${room.regionId}|${room.serverId}|${room.roomName}|${participant.identity}`;
+ const seen = previous[key];
+ const sighting =
+ seen !== undefined && seen.joinedAt === participant.joinedAt
+ ? seen
+ : {joinedAt: participant.joinedAt, firstSeenAt: now};
+ sightings[key] = sighting;
+ if (now - sighting.firstSeenAt >= VOICE_PARTICIPANT_SETTLE_MS) {
+ due.push({key, room, identity: participant.identity, gatewayKey, ...sighting});
+ }
+ }
+ return true;
+}
+
+async function gatewayParticipantKeys(deps: VoiceParticipantSweepDeps, room: SweepRoom): Promise<Set<string> | null> {
+ try {
+ const {voiceStates} = await deps.gatewayService.getVoiceStatesForChannel({
+ guildId: isDMRoom(room.context) ? undefined : room.context.guildId,
+ channelId: room.context.channelId,
+ });
+ return new Set(voiceStates.map((voiceState) => `${voiceState.userId}|${voiceState.connectionId}`));
+ } catch (error) {
+ if (error instanceof UnknownGuildError || error instanceof UnknownChannelError) {
+ return new Set();
+ }
+ deps.logger.warn({error, roomName: room.roomName}, 'Voice participant sweep could not read gateway voice states');
+ return null;
+ }
+}
+
+function participantGatewayKey(identity: string, metadata: string): string | null {
+ const parsed = metadata ? parseParticipantMetadataWithRaw(metadata) : null;
+ if (parsed) {
+ return `${parsed.context.userId}|${parsed.context.connectionId}`;
+ }
+ const match = IDENTITY_PATTERN.exec(identity);
+ return match ? `${match[1]}|${match[2]}` : null;
+}
+
+async function removeIfStillMissing(
+ deps: VoiceParticipantSweepDeps,
+ participant: DueParticipant,
+): Promise<'removed' | 'present' | 'unknown'> {
+ const {room} = participant;
+ const known = await gatewayParticipantKeys(deps, room);
+ if (known === null) {
+ return 'unknown';
+ }
+ if (participant.gatewayKey !== null && known.has(participant.gatewayKey)) {
+ return 'present';
+ }
+ const ref = {
+ regionId: room.regionId,
+ serverId: room.serverId,
+ roomName: room.roomName,
+ identity: participant.identity,
+ };
+ const current = await deps.liveKitService.getParticipant(ref);
+ if (current.status === 'error') {
+ return 'unknown';
+ }
+ if (current.participant?.joinedAt !== participant.joinedAt) {
+ return 'present';
+ }
+ const logContext = {
+ regionId: room.regionId,
+ serverId: room.serverId,
+ roomName: room.roomName,
+ participantIdentity: participant.identity,
+ joinedAt: participant.joinedAt,
+ missingForMs: deps.now() - participant.firstSeenAt,
+ };
+ if (deps.dryRun) {
+ deps.logger.info(logContext, 'Voice participant sweep would disconnect a participant with no voice state');
+ return 'unknown';
+ }
+ await deps.liveKitService.removeParticipant(ref);
+ voiceParticipantsDisconnectedTotal.inc('reason="sweep"');
+ deps.logger.info(logContext, 'Voice participant sweep disconnected a participant with no voice state');
+ return 'removed';
+}
diff --git a/fluxer_api/src/api/voice/VoiceService.ts b/fluxer_api/src/api/voice/VoiceService.ts
index 10ad68e3f..7a55d6a61 100644
--- a/fluxer_api/src/api/voice/VoiceService.ts
+++ b/fluxer_api/src/api/voice/VoiceService.ts
@@ -426,6 +426,18 @@ export class VoiceService {
const {guildId, channelId, userId, connectionId} = params;
const pinnedServer = await this.voiceRoomStore.getPinnedRoomServer(guildId, channelId);
if (!pinnedServer) {
+ await Promise.allSettled(
+ this.liveKitService.listServers().map((server) =>
+ this.liveKitService.disconnectParticipant({
+ userId,
+ guildId,
+ channelId,
+ connectionId,
+ regionId: server.regionId,
+ serverId: server.serverId,
+ }),
+ ),
+ );
return;
}
await this.liveKitService.disconnectParticipant({
diff --git a/fluxer_api/src/api/voice/tests/VoiceParticipantSweep.test.ts b/fluxer_api/src/api/voice/tests/VoiceParticipantSweep.test.ts
new file mode 100644
index 000000000..60fb9ca2d
--- /dev/null
+++ b/fluxer_api/src/api/voice/tests/VoiceParticipantSweep.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {
+ sweepVoiceParticipants,
+ type VoiceParticipantSightings,
+ type VoiceParticipantSweepDeps,
+} from '@app/api/voice/VoiceParticipantSweep';
+import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
+import {describe, expect, it} from 'vitest';
+
+class QuietLogger implements LoggerInterface {
+ trace(): void {}
+ debug(): void {}
+ info(): void {}
+ warn(): void {}
+ error(): void {}
+ fatal(): void {}
+ child(): LoggerInterface {
+ return this;
+ }
+}
+
+const ROOM = 'guild_10_channel_20';
+const KNOWN = 'user_1_known';
+const STRAY = 'user_2_stray';
+
+function createHarness() {
+ const state = {
+ now: 0,
+ joinedAt: 1000,
+ gatewayReads: 0,
+ strayKnownFromRead: Number.POSITIVE_INFINITY,
+ removed: [] as Array<string>,
+ };
+ const deps: VoiceParticipantSweepDeps = {
+ logger: new QuietLogger(),
+ now: () => state.now,
+ dryRun: false,
+ liveKitService: {
+ listServers: () => [{regionId: 'eu', serverId: 'eu-1'}],
+ listRooms: async () => ({status: 'ok', rooms: [{name: ROOM, numParticipants: 2}]}),
+ listParticipants: async () => ({
+ status: 'ok',
+ participants: [
+ {identity: KNOWN, joinedAt: 500, metadata: ''},
+ {identity: STRAY, joinedAt: state.joinedAt, metadata: ''},
+ ],
+ }),
+ getParticipant: async ({identity}) => ({
+ status: 'ok',
+ participant: {joinedAt: identity === STRAY ? state.joinedAt : 500, metadata: ''},
+ }),
+ removeParticipant: async ({identity}) => {
+ state.removed.push(identity);
+ },
+ },
+ gatewayService: {
+ getVoiceStatesForChannel: async () => {
+ state.gatewayReads += 1;
+ const known = [{connectionId: 'known', userId: '1', channelId: '20'}];
+ if (state.gatewayReads >= state.strayKnownFromRead) {
+ known.push({connectionId: 'stray', userId: '2', channelId: '20'});
+ }
+ return {voiceStates: known};
+ },
+ },
+ };
+ let sightings: VoiceParticipantSightings = {};
+ const sweepAt = async (minute: number) => {
+ state.now = minute * 60_000;
+ const result = await sweepVoiceParticipants(deps, sightings);
+ sightings = result.sightings;
+ return result;
+ };
+ return {state, sweepAt};
+}
+
+describe('sweepVoiceParticipants', () => {
+ it('disconnects a participant only after it stays unknown with the same join time for two minutes', async () => {
+ const {state, sweepAt} = createHarness();
+ expect((await sweepAt(0)).removed).toBe(0);
+ expect((await sweepAt(1)).removed).toBe(0);
+ const settled = await sweepAt(2);
+ expect(settled.removed).toBe(1);
+ expect(state.removed).toEqual([STRAY]);
+ });
+
+ it('starts over when the participant rejoins with a new join time', async () => {
+ const {state, sweepAt} = createHarness();
+ await sweepAt(0);
+ await sweepAt(1);
+ state.joinedAt = 2000;
+ expect((await sweepAt(2)).removed).toBe(0);
+ expect((await sweepAt(3)).removed).toBe(0);
+ expect((await sweepAt(4)).removed).toBe(1);
+ });
+
+ it('keeps a participant the gateway knows by the time of removal', async () => {
+ const {state, sweepAt} = createHarness();
+ await sweepAt(0);
+ state.strayKnownFromRead = state.gatewayReads + 2;
+ expect((await sweepAt(2)).removed).toBe(0);
+ expect(state.removed).toEqual([]);
+ });
+});
diff --git a/fluxer_api/src/api/worker/WorkerLaneConfig.ts b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
index b1204853c..144d24926 100644
--- a/fluxer_api/src/api/worker/WorkerLaneConfig.ts
+++ b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
@@ -96,6 +96,7 @@ const LANE_CONFIG = {
'pollGooglePlayVoidedPurchases',
'pollAppStoreNotificationHistory',
'prunePostgresKvTtl',
+ 'sweepVoiceParticipants',
'refreshSearchIndex',
'seedThreadPermissions',
'archiveInactiveThreads',
diff --git a/fluxer_api/src/api/worker/WorkerMain.ts b/fluxer_api/src/api/worker/WorkerMain.ts
index 6db42a729..4702c1d5d 100644
--- a/fluxer_api/src/api/worker/WorkerMain.ts
+++ b/fluxer_api/src/api/worker/WorkerMain.ts
@@ -145,6 +145,10 @@ function registerCronJobs(cron: CronScheduler, jobsStreamMaxAgeMs: number, kvCli
);
}
cron.upsert('prunePostgresKvTtl', 'prunePostgresKvTtl', {}, '0 */5 * * * *', {ledger: false});
+ cron.upsert('sweepVoiceParticipants', 'sweepVoiceParticipants', {}, '30 * * * * *', {
+ ledger: false,
+ enabled: () => Config.voice.enabled && Config.voice.participantSweepEnabled,
+ });
cron.upsert('syncDiscoveryIndex', 'syncDiscoveryIndex', {}, '0 */15 * * * *', {ledger: false});
if (Config.blocklistFeeds.enabled) {
cron.upsert('syncUrlBlocklists', 'syncUrlBlocklists', {}, '0 0 */6 * * *', {ledger: true});
diff --git a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
index c175e9b8d..f7c3a1f6b 100644
--- a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
+++ b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
@@ -76,6 +76,7 @@ import seedThreadPermissions from '@app/api/worker/tasks/SeedThreadPermissions';
import sendBillingEmail from '@app/api/worker/tasks/SendBillingEmail';
import sendOperatorPassWithdrawalReceipt from '@app/api/worker/tasks/SendOperatorPassWithdrawalReceipt';
import {sendSystemDm} from '@app/api/worker/tasks/SendSystemDm';
+import sweepVoiceParticipants from '@app/api/worker/tasks/SweepVoiceParticipants';
import syncCrosspostCopies from '@app/api/worker/tasks/SyncCrosspostCopies';
import syncCrosspostedMessage from '@app/api/worker/tasks/SyncCrosspostedMessage';
import syncDiscoveryIndex from '@app/api/worker/tasks/SyncDiscoveryIndex';
@@ -164,6 +165,7 @@ export const workerTasks: Record<WorkerTaskName, WorkerTaskHandler> = {
pollGooglePlayVoidedPurchases,
pollAppStoreNotificationHistory,
prunePostgresKvTtl,
+ sweepVoiceParticipants,
pruneGuildVisits: pruneGuildVisitsTask,
refreshSearchIndex,
seedThreadPermissions,
diff --git a/fluxer_api/src/api/worker/tasks/SweepVoiceParticipants.ts b/fluxer_api/src/api/worker/tasks/SweepVoiceParticipants.ts
new file mode 100644
index 000000000..5fd1496d7
--- /dev/null
+++ b/fluxer_api/src/api/worker/tasks/SweepVoiceParticipants.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {randomUUID} from 'node:crypto';
+import {Config} from '@app/api/Config';
+import {sweepVoiceParticipants, type VoiceParticipantSightings} from '@app/api/voice/VoiceParticipantSweep';
+import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+
+const LOCK_KEY = 'voice:participant_sweep:lock';
+const SIGHTINGS_KEY = 'voice:participant_sweep:sightings';
+const LOCK_TTL_SECONDS = 300;
+const SIGHTINGS_TTL_SECONDS = 900;
+
+function parseSightings(raw: string | null): VoiceParticipantSightings {
+ if (raw === null) {
+ return {};
+ }
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return typeof parsed === 'object' && parsed !== null ? (parsed as VoiceParticipantSightings) : {};
+ } catch {
+ return {};
+ }
+}
+
+const sweepVoiceParticipantsTask: WorkerTaskHandler = async (_payload, helpers) => {
+ const {kvClient, liveKitService, gatewayService} = getWorkerDependencies();
+ const lockToken = randomUUID();
+ if (!(await kvClient.acquireLock(LOCK_KEY, lockToken, LOCK_TTL_SECONDS))) {
+ helpers.logger.debug('Voice participant sweep already running elsewhere');
+ return;
+ }
+ try {
+ const previous = parseSightings(await kvClient.get(SIGHTINGS_KEY));
+ const result = await sweepVoiceParticipants(
+ {
+ liveKitService,
+ gatewayService,
+ logger: helpers.logger,
+ now: () => Date.now(),
+ dryRun: Config.voice.participantSweepDryRun,
+ },
+ previous,
+ );
+ await kvClient.setex(SIGHTINGS_KEY, SIGHTINGS_TTL_SECONDS, JSON.stringify(result.sightings));
+ const {sightings: _sightings, ...summary} = result;
+ if (summary.candidates > 0 || summary.skippedRooms > 0) {
+ helpers.logger.info(summary, 'Voice participant sweep finished');
+ }
+ } finally {
+ await kvClient.releaseLock(LOCK_KEY, lockToken);
+ }
+};
+
+export default sweepVoiceParticipantsTask;
diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdx
index f3442701f..9e70dc234 100644
--- a/fluxer_docs/src/content/docs/operator/environment.mdx
+++ b/fluxer_docs/src/content/docs/operator/environment.mdx
@@ -292,6 +292,14 @@ Whether the API accepts a voice server joining with an endpoint that resolves to
How often each API node checks every active voice server, in milliseconds. A server that fails two checks in a row gets no new calls until a check passes. Set it to `0` to turn the checks off. When it's empty, the API checks every 15 seconds. With rexctl, use `rexctl config set FLUXER_VOICE_HEALTH_INTERVAL_MS`.
+### `FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED`
+
+Whether a worker compares each voice server's call participants with the gateway's call state every minute and disconnects connections the gateway has not known for two minutes. Use `true` or `false`. When it's empty, the check runs. With rexctl, use `rexctl config set FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED`.
+
+### `FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN`
+
+Whether the voice participant check from `FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED` only logs the connections it would disconnect. Use `true` or `false`. When it's empty, the check only logs them. With rexctl, use `rexctl config set FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN`.
+
### `FLUXER_LIVEKIT_TCP_PORT`
The TCP port for voice and video. The default is `7881`. With rexctl, use `rexctl config set voice.tcp_port`.
diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.go
index 9bbb40c71..c7b8648df 100644
--- a/fluxer_rexctl/internal/instance/envvars.go
+++ b/fluxer_rexctl/internal/instance/envvars.go
@@ -99,6 +99,8 @@ var envVars = []envVar{
{"FLUXER_VOICE_P2P_STUN_URLS", "voice", "STUN URLs for peer-to-peer calls, separated by commas, such as `stun:stun.example.com:3478`. When it's empty, peer-to-peer calls work only between devices with a direct route to each other, such as on one local network."},
{"FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS", "voice", "Whether the API accepts a voice server joining with an endpoint that resolves to a private address. Use `true` or `false`. Set it to `true` only for tests and private networks."},
{"FLUXER_VOICE_HEALTH_INTERVAL_MS", "voice", "How often each API node checks every active voice server, in milliseconds. A server that fails two checks in a row gets no new calls until a check passes. Set it to `0` to turn the checks off. When it's empty, the API checks every 15 seconds."},
+ {"FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED", "voice", "Whether a worker compares each voice server's call participants with the gateway's call state every minute and disconnects connections the gateway has not known for two minutes. Use `true` or `false`. When it's empty, the check runs."},
+ {"FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN", "voice", "Whether the voice participant check from FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED only logs the connections it would disconnect. Use `true` or `false`. When it's empty, the check only logs them."},
{"FLUXER_LIVEKIT_TCP_PORT", "voice", ""},
{"FLUXER_LIVEKIT_UDP_PORT", "voice", ""},
{"FLUXER_LIVEKIT_NODE_IP", "voice", "Set FLUXER_LIVEKIT_USE_EXTERNAL_IP to `false` with it."},
diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.example
index c9396b675..24bc0e2a3 100644
--- a/fluxer_rexctl/internal/stack/files/.env.example
+++ b/fluxer_rexctl/internal/stack/files/.env.example
@@ -493,6 +493,19 @@ FLUXER_VAPID_PRIVATE_KEY=
# rexctl: rexctl config set FLUXER_VOICE_HEALTH_INTERVAL_MS
# FLUXER_VOICE_HEALTH_INTERVAL_MS=
+# Whether a worker compares each voice server's call participants with the
+# gateway's call state every minute and disconnects connections the gateway
+# has not known for two minutes. Use true or false. When it's empty, the check
+# runs.
+# rexctl: rexctl config set FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED
+# FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED=
+
+# Whether the voice participant check from
+# FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED only logs the connections it would
+# disconnect. Use true or false. When it's empty, the check only logs them.
+# rexctl: rexctl config set FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN
+# FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN=
+
# The TCP port for voice and video.
# default: 7881
# rexctl: rexctl config set voice.tcp_port
diff --git a/fluxer_rexctl/internal/stack/files/docker-compose.yml b/fluxer_rexctl/internal/stack/files/docker-compose.yml
index 58f95eda4..4cc3b7f80 100644
--- a/fluxer_rexctl/internal/stack/files/docker-compose.yml
+++ b/fluxer_rexctl/internal/stack/files/docker-compose.yml
@@ -124,6 +124,8 @@ x-fluxer-env: &fluxer-env
FLUXER_LIVEKIT_TURN_SERVERS: ${FLUXER_LIVEKIT_TURN_SERVERS:-[]}
FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS: ${FLUXER_VOICE_JOIN_ALLOW_PRIVATE_ENDPOINTS:-}
FLUXER_VOICE_HEALTH_INTERVAL_MS: ${FLUXER_VOICE_HEALTH_INTERVAL_MS:-}
+ FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED: ${FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED:-}
+ FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN: ${FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN:-}
FLUXER_KLIPY_API_KEY: ${FLUXER_KLIPY_API_KEY:-}
FLUXER_YOUTUBE_API_KEY: ${FLUXER_YOUTUBE_API_KEY:-}
diff --git a/packages/config/src/MasterConfig.ts b/packages/config/src/MasterConfig.ts
index e1f3d9926..a39cdb023 100644
--- a/packages/config/src/MasterConfig.ts
+++ b/packages/config/src/MasterConfig.ts
@@ -240,6 +240,8 @@ export interface MasterConfig {
turn_servers?: Array<VoiceTurnServerConfig>;
join_allow_private_endpoints?: boolean;
health_interval_ms?: number;
+ participant_sweep_enabled?: boolean;
+ participant_sweep_dry_run?: boolean;
};
search: {
engine: 'elasticsearch' | 'meilisearch' | 'none';
diff --git a/packages/config/src/config_loader/EnvironmentOverrides.ts b/packages/config/src/config_loader/EnvironmentOverrides.ts
index 9ea51a1a8..6e7be8d2e 100644
--- a/packages/config/src/config_loader/EnvironmentOverrides.ts
+++ b/packages/config/src/config_loader/EnvironmentOverrides.ts
@@ -203,6 +203,14 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {
parse: parseBoolean,
},
FLUXER_VOICE_HEALTH_INTERVAL_MS: {path: ['integrations', 'voice', 'health_interval_ms'], parse: parseInteger},
+ FLUXER_VOICE_PARTICIPANT_SWEEP_ENABLED: {
+ path: ['integrations', 'voice', 'participant_sweep_enabled'],
+ parse: parseBoolean,
+ },
+ FLUXER_VOICE_PARTICIPANT_SWEEP_DRY_RUN: {
+ path: ['integrations', 'voice', 'participant_sweep_dry_run'],
+ parse: parseBoolean,
+ },
FLUXER_SEARCH_ENGINE: {path: ['integrations', 'search', 'engine']},
FLUXER_SEARCH_URL: {path: ['integrations', 'search', 'url']},
FLUXER_SEARCH_API_KEY: {path: ['integrations', 'search', 'api_key']},