A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(voice): keep server mutes in sync with the media server (#3904)
Hampuse9b3def9ff47
diff --git a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.tsindex ac3d20aab..7ed34f29f 100644--- a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts+++ b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts@@ -18,8 +18,6 @@ export class DisabledLiveKitService implements ILiveKitService {async updateParticipant(): Promise<void> {}- async updateParticipantPermissions(): Promise<void> {}-async muteMicrophoneTrack(): Promise<void> {}async disconnectParticipant(): Promise<void> {}diff --git a/fluxer_api/src/api/infrastructure/ILiveKitService.ts b/fluxer_api/src/api/infrastructure/ILiveKitService.tsindex 781ea6ed9..028369e39 100644--- a/fluxer_api/src/api/infrastructure/ILiveKitService.ts+++ b/fluxer_api/src/api/infrastructure/ILiveKitService.ts@@ -43,19 +43,6 @@ export interface MuteMicrophoneTrackParams {trackSid: string;}-export interface UpdateParticipantPermissionsParams {- userId: UserID;- guildId?: GuildID;- channelId: ChannelID;- connectionId: string;- regionId: string;- serverId: string;- canSpeak: boolean;- canStream: boolean;- canVideo: boolean;- deaf?: boolean;-}-export interface DisconnectParticipantParams {userId: UserID;guildId?: GuildID;@@ -134,8 +121,6 @@ export abstract class ILiveKitService {abstract updateParticipant(params: UpdateParticipantParams): Promise<void>;- abstract updateParticipantPermissions(params: UpdateParticipantPermissionsParams): Promise<void>;-abstract muteMicrophoneTrack(params: MuteMicrophoneTrackParams): Promise<void>;abstract disconnectParticipant(params: DisconnectParticipantParams): Promise<void>;diff --git a/fluxer_api/src/api/infrastructure/LiveKitService.ts b/fluxer_api/src/api/infrastructure/LiveKitService.tsindex 593b5b3ec..8a9f6f328 100644--- a/fluxer_api/src/api/infrastructure/LiveKitService.ts+++ b/fluxer_api/src/api/infrastructure/LiveKitService.ts@@ -15,13 +15,12 @@ import {type MuteMicrophoneTrackParams,type SetParticipantPermissionParams,type UpdateParticipantParams,- type UpdateParticipantPermissionsParams,} from '@app/api/infrastructure/ILiveKitService';import {Logger} from '@app/api/Logger';import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';import {resolveRoomServiceEndpoint, toHttpUrl} from '@app/api/voice/VoiceServerEndpoints';import type {VoiceTopology} from '@app/api/voice/VoiceTopology';-import {AccessToken, RoomServiceClient, type TrackInfo, TrackSource} from 'livekit-server-sdk';+import {AccessToken, RoomServiceClient, TrackSource} from 'livekit-server-sdk';interface ServerClientConfig {endpoint: string;@@ -123,7 +122,7 @@ export class LiveKitService extends ILiveKitService {} else {metadata['dm_call'] = 'true';}- const canPublishSources = computeLiveKitPublishSources({canSpeak, canStream, canVideo});+ const canPublishSources = computeLiveKitPublishSources({canSpeak: canSpeak && !mute, canStream, canVideo});const accessToken = new AccessToken(server.apiKey, server.apiSecret, {identity: participantIdentity,metadata: JSON.stringify(metadata),@@ -143,75 +142,63 @@ export class LiveKitService extends ILiveKitService {async updateParticipant(params: UpdateParticipantParams): Promise<void> {const {userId, guildId, channelId, connectionId, regionId, serverId, mute, deaf} = params;+ if (mute === undefined && deaf === undefined) {+ return;+ }const roomName = this.getRoomName(guildId, channelId);const participantIdentity = this.getParticipantIdentity(userId, connectionId);const server = this.resolveServerClient(regionId, serverId);- try {- const participants = await server.roomServiceClient.listParticipants(roomName);- const participant = participants.find((p) => p.identity === participantIdentity);- if (!participant) {- return;- }- if (mute !== undefined) {- const tracks =- (await this.setServerMuteAttribute(server, roomName, participantIdentity, mute)) ?? participant.tracks;- for (const track of tracks) {- if (track.source === TrackSource.MICROPHONE && track.sid) {- await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, mute);- }- }+ const participants = await server.roomServiceClient.listParticipants(roomName);+ const participant = participants.find((p) => p.identity === participantIdentity);+ if (!participant) {+ return;+ }+ const wasServerMuted = participant.attributes[SERVER_MUTE_ATTRIBUTE] === 'true';+ const serverMuted = mute ?? wasServerMuted;+ const deafened = deaf ?? participant.permission?.canSubscribe === false;+ const currentSources = participant.permission?.canPublishSources ?? [];+ const canPublishSources = computeLiveKitPublishSources({+ canSpeak: (params.canSpeak ?? currentSources.includes(TrackSource.MICROPHONE)) && !serverMuted,+ canStream: params.canStream ?? currentSources.includes(TrackSource.SCREEN_SHARE),+ canVideo: params.canVideo ?? currentSources.includes(TrackSource.CAMERA),+ });+ const permission = {+ canPublish: !deafened && canPublishSources.length > 0,+ canSubscribe: !deafened,+ canPublishSources,+ };+ if (serverMuted !== wasServerMuted) {+ await this.setServerMuteAttribute(server, roomName, participantIdentity, serverMuted);+ }+ const updated = await server.roomServiceClient.updateParticipant(+ roomName,+ participantIdentity,+ undefined,+ permission,+ );+ for (const track of updated.tracks ?? participant.tracks) {+ if (!track.sid) {+ continue;}- if (deaf !== undefined) {- const canPublishSources = computeLiveKitPublishSources({- canSpeak: params.canSpeak ?? true,- canStream: params.canStream ?? true,- canVideo: params.canVideo ?? true,- });- await server.roomServiceClient.updateParticipant(roomName, participantIdentity, undefined, {- canPublish: !deaf && canPublishSources.length > 0,- canSubscribe: !deaf,- canPublishSources,- });+ if (!canPublishSources.includes(track.source)) {+ await this.setTrackMuted(server, roomName, participantIdentity, track.sid, true);+ } else if (track.source === TrackSource.MICROPHONE && wasServerMuted) {+ await this.setTrackMuted(server, roomName, participantIdentity, track.sid, false);}- } catch (error) {- Logger.error({error}, 'Error updating LiveKit participant');}}- async updateParticipantPermissions(params: UpdateParticipantPermissionsParams): Promise<void> {- const {userId, guildId, channelId, connectionId, regionId, serverId, canSpeak, canStream, canVideo, deaf} = params;- const roomName = this.getRoomName(guildId, channelId);- const participantIdentity = this.getParticipantIdentity(userId, connectionId);- const server = this.resolveServerClient(regionId, serverId);+ private async setTrackMuted(+ server: ServerClientConfig,+ roomName: string,+ participantIdentity: string,+ trackSid: string,+ muted: boolean,+ ): Promise<void> {try {- const participants = await server.roomServiceClient.listParticipants(roomName);- const participant = participants.find((p) => p.identity === participantIdentity);- if (!participant) {- Logger.warn({participantIdentity, roomName}, 'Participant not found for permission update');- return;- }- const canPublishSources = computeLiveKitPublishSources({canSpeak, canStream, canVideo});- const participantPermission = {- canPublish: !deaf && canPublishSources.length > 0,- canPublishSources,- ...(deaf !== undefined ? {canSubscribe: !deaf} : {}),- };- await server.roomServiceClient.updateParticipant(roomName, participantIdentity, undefined, {- ...participantPermission,- });- const revokedSources = computeLiveKitPublishSources({- canSpeak: !canSpeak,- canStream: !canStream,- canVideo: !canVideo,- });- for (const track of participant.tracks) {- if (track.sid && revokedSources.includes(track.source)) {- await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, true);- }- }- Logger.debug({participantIdentity, roomName, canSpeak, canStream, canVideo}, 'Updated participant permissions');+ await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, trackSid, muted);} catch (error) {- Logger.error({error}, 'Error updating LiveKit participant permissions');+ Logger.debug({error, participantIdentity, roomName, trackSid, muted}, 'LiveKit declined track mute change');}}@@ -220,15 +207,13 @@ export class LiveKitService extends ILiveKitService {roomName: string,participantIdentity: string,mute: boolean,- ): Promise<Array<TrackInfo> | null> {+ ): Promise<void> {try {- const updated = await server.roomServiceClient.updateParticipant(roomName, participantIdentity, {+ await server.roomServiceClient.updateParticipant(roomName, participantIdentity, {attributes: {[SERVER_MUTE_ATTRIBUTE]: mute ? 'true' : ''},});- return updated.tracks;} catch (error) {Logger.warn({error, participantIdentity, roomName}, 'Failed to record server mute on LiveKit participant');- return null;}}diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.tsindex 2da2394db..da5b72d9c 100644--- a/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts+++ b/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts@@ -106,16 +106,25 @@ describe('LiveKitService updateParticipant mute', () => {serverId: 'region-1-server-1',};- function roomServiceClient(- listedTracks: Array<{sid: string; source: TrackSource}>,- updatedTracks: typeof listedTracks,- ) {+ const allSources = [+ TrackSource.MICROPHONE,+ TrackSource.CAMERA,+ TrackSource.SCREEN_SHARE,+ TrackSource.SCREEN_SHARE_AUDIO,+ ];++ function roomServiceClient(participant: {+ attributes: Record<string, string>;+ permission?: {canSubscribe: boolean; canPublishSources: Array<TrackSource>};+ tracks: Array<{sid: string; source: TrackSource}>;+ updatedTracks?: Array<{sid: string; source: TrackSource}>;+ }) {const calls: Array<Array<unknown>> = [];const client = {- listParticipants: async () => [{identity: 'user_3_conn-1', tracks: listedTracks}],+ listParticipants: async () => [{identity: 'user_3_conn-1', ...participant}],updateParticipant: async (...args: Array<unknown>) => {calls.push(['updateParticipant', ...args]);- return {identity: 'user_3_conn-1', tracks: updatedTracks};+ return {identity: 'user_3_conn-1', tracks: participant.updatedTracks ?? participant.tracks};},mutePublishedTrack: async (...args: Array<unknown>) => {calls.push(['mutePublishedTrack', ...args]);@@ -124,33 +133,194 @@ describe('LiveKitService updateParticipant mute', () => {return {client, calls};}- it('records the mute on the participant and mutes every current microphone track', async () => {- const {client, calls} = roomServiceClient(- [{sid: 'TR_old', source: TrackSource.MICROPHONE}],- [+ it('records the mute, revokes the microphone, then mutes every remaining microphone track', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {},+ tracks: [{sid: 'TR_old', source: TrackSource.MICROPHONE}],+ updatedTracks: [{sid: 'TR_old', source: TrackSource.MICROPHONE},{sid: 'TR_new', source: TrackSource.MICROPHONE},],- );+ });const service = createServiceWithRoomServiceClient(client);- await service.updateParticipant({...params, mute: true});+ await service.updateParticipant({+ ...params,+ mute: true,+ deaf: false,+ canSpeak: true,+ canStream: true,+ canVideo: true,+ });expect(calls).toEqual([['updateParticipant', 'guild_1_channel_2', 'user_3_conn-1', {attributes: {server_mute: 'true'}}],+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {+ canPublish: true,+ canSubscribe: true,+ canPublishSources: [TrackSource.CAMERA, TrackSource.SCREEN_SHARE, TrackSource.SCREEN_SHARE_AUDIO],+ },+ ],['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_old', true],['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_new', true],]);});- it('clears the recorded mute on unmute', async () => {- const {client, calls} = roomServiceClient([], []);+ it('revokes the microphone even when a track mute fails', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {},+ tracks: [+ {sid: 'TR_cam', source: TrackSource.CAMERA},+ {sid: 'TR_mic', source: TrackSource.MICROPHONE},+ ],+ });+ const service = createServiceWithRoomServiceClient({+ ...client,+ mutePublishedTrack: async (...args: Array<unknown>) => {+ calls.push(['mutePublishedTrack', ...args]);+ throw new Error('not_found');+ },+ });++ await service.updateParticipant({+ ...params,+ mute: true,+ deaf: false,+ canSpeak: true,+ canStream: true,+ canVideo: false,+ });++ expect(calls).toEqual([+ ['updateParticipant', 'guild_1_channel_2', 'user_3_conn-1', {attributes: {server_mute: 'true'}}],+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {+ canPublish: true,+ canSubscribe: true,+ canPublishSources: [TrackSource.SCREEN_SHARE, TrackSource.SCREEN_SHARE_AUDIO],+ },+ ],+ ['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_cam', true],+ ['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_mic', true],+ ]);+ });++ it('clears the recorded mute before restoring microphone publishing', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {server_mute: 'true'},+ tracks: [{sid: 'TR_mic', source: TrackSource.MICROPHONE}],+ });const service = createServiceWithRoomServiceClient(client);- await service.updateParticipant({...params, mute: false});+ await service.updateParticipant({+ ...params,+ mute: false,+ deaf: false,+ canSpeak: true,+ canStream: true,+ canVideo: true,+ });expect(calls).toEqual([['updateParticipant', 'guild_1_channel_2', 'user_3_conn-1', {attributes: {server_mute: ''}}],+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {canPublish: true, canSubscribe: true, canPublishSources: allSources},+ ],+ ['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_mic', false],+ ]);+ });++ it('leaves the microphone of a member who was never server muted alone', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {},+ tracks: [{sid: 'TR_mic', source: TrackSource.MICROPHONE}],+ });+ const service = createServiceWithRoomServiceClient(client);++ await service.updateParticipant({+ ...params,+ mute: false,+ deaf: false,+ canSpeak: true,+ canStream: true,+ canVideo: true,+ });++ expect(calls).toEqual([+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {canPublish: true, canSubscribe: true, canPublishSources: allSources},+ ],+ ]);+ });++ it('keeps the sources a muted member already has when the caller sends no permissions', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {server_mute: 'true'},+ permission: {canSubscribe: true, canPublishSources: []},+ tracks: [],+ });+ const service = createServiceWithRoomServiceClient(client);++ await service.updateParticipant({...params, mute: true, deaf: false});++ expect(calls).toEqual([+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {canPublish: false, canSubscribe: true, canPublishSources: []},+ ],+ ]);+ });++ it('mutes camera and screen tracks a permission sync no longer allows', async () => {+ const {client, calls} = roomServiceClient({+ attributes: {},+ tracks: [+ {sid: 'TR_mic', source: TrackSource.MICROPHONE},+ {sid: 'TR_cam', source: TrackSource.CAMERA},+ {sid: 'TR_screen', source: TrackSource.SCREEN_SHARE},+ ],+ });+ const service = createServiceWithRoomServiceClient(client);++ await service.updateParticipant({+ ...params,+ mute: false,+ deaf: false,+ canSpeak: true,+ canStream: false,+ canVideo: false,+ });++ expect(calls).toEqual([+ [+ 'updateParticipant',+ 'guild_1_channel_2',+ 'user_3_conn-1',+ undefined,+ {canPublish: true, canSubscribe: true, canPublishSources: [TrackSource.MICROPHONE]},+ ],+ ['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_cam', true],+ ['mutePublishedTrack', 'guild_1_channel_2', 'user_3_conn-1', 'TR_screen', true],]);});});@@ -166,13 +336,25 @@ describe('LiveKitService createToken mute', () => {serverId: 'region-1-server-1',};- async function tokenAttributes(mute: boolean): Promise<Record<string, string> | undefined> {+ async function tokenPayload(mute: boolean) {const service = createServiceWithRoomServiceClient({});const {token} = await service.createToken({...params, mute});- const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString());- return payload.attributes;+ return JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString());+ }++ async function tokenAttributes(mute: boolean): Promise<Record<string, string> | undefined> {+ return (await tokenPayload(mute)).attributes;}+ it('withholds microphone publishing from a token issued to a muted member', async () => {+ expect((await tokenPayload(true)).video.canPublishSources).toEqual([+ 'camera',+ 'screen_share',+ 'screen_share_audio',+ ]);+ expect((await tokenPayload(false)).video.canPublishSources).toContain('microphone');+ });+it('records the server mute on a token issued to a muted member', async () => {expect(await tokenAttributes(true)).toEqual({server_mute: 'true'});});diff --git a/fluxer_api/src/api/rpc/RpcService.ts b/fluxer_api/src/api/rpc/RpcService.tsindex 61bfb500f..03fe505cc 100644--- a/fluxer_api/src/api/rpc/RpcService.ts+++ b/fluxer_api/src/api/rpc/RpcService.ts@@ -466,22 +466,6 @@ export class RpcService {data: {success: true},};}- case 'voice_update_participant_permissions': {- await this.requireVoiceService().updateParticipantPermissions({- guildId: request.guild_id !== undefined ? createGuildID(request.guild_id) : undefined,- channelId: createChannelID(request.channel_id),- userId: createUserID(request.user_id),- connectionId: request.connection_id,- canSpeak: request.can_speak,- canStream: request.can_stream,- canVideo: request.can_video,- deaf: request.deaf,- });- return {- type: 'voice_update_participant_permissions',- data: {success: true},- };- }case 'kick_temporary_member': {const success = await this.kickTemporaryMember({userId: createUserID(request.user_id),diff --git a/fluxer_api/src/api/voice/VoiceService.ts b/fluxer_api/src/api/voice/VoiceService.tsindex 333864111..92dc77d51 100644--- a/fluxer_api/src/api/voice/VoiceService.ts+++ b/fluxer_api/src/api/voice/VoiceService.ts@@ -376,8 +376,10 @@ export class VoiceService {{errorCode: result.errorCode, guildId, channelId},'Failed to list participants for self mute/deaf update',);- return;+ if (result.serverMissing) return;+ throw new Error(`Failed to list voice participants: ${result.errorCode}`);}+ let failures = 0;for (const participant of result.participants) {const parts = participant.identity.split('_');if (parts.length >= 2 && parts[0] === 'user') {@@ -414,10 +416,14 @@ export class VoiceService {},'Failed to update participant',);+ failures += 1;}}}}+ if (failures > 0) {+ throw new Error(`Failed to update ${failures} voice participant connection(s)`);+ }}async disconnectParticipant(params: {@@ -453,35 +459,6 @@ export class VoiceService {});}- async updateParticipantPermissions(params: {- guildId?: GuildID;- channelId: ChannelID;- userId: UserID;- connectionId: string;- canSpeak: boolean;- canStream: boolean;- canVideo: boolean;- deaf?: boolean;- }): Promise<void> {- const {guildId, channelId, userId, connectionId, canSpeak, canStream, canVideo, deaf} = params;- const pinnedServer = await this.voiceRoomStore.getPinnedRoomServer(guildId, channelId);- if (!pinnedServer) {- return;- }- await this.liveKitService.updateParticipantPermissions({- userId,- guildId,- channelId,- connectionId,- regionId: pinnedServer.regionId,- serverId: pinnedServer.serverId,- canSpeak,- canStream,- canVideo,- deaf,- });- }-private async assertVoiceReach(user: User, channelType: number, guildId: GuildID | null | undefined): Promise<void> {if (channelType === ChannelTypes.GUILD_VOICE) {const guild = guildId ? await this.guildRepository.findUnique(guildId) : null;diff --git a/fluxer_gateway/src/guild/voice/guild_voice_member.erl b/fluxer_gateway/src/guild/voice/guild_voice_member.erlindex 9a110f587..abce8eaea 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_member.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_member.erl@@ -18,13 +18,18 @@-type guild_reply(T) :: {reply, T | {error, atom(), atom()}, guild_state()}.-type member() :: map().-type voice_state() :: map().--type request() :: #{- user_id := integer(),- mute := boolean(),- deaf := boolean()-}.+-type request() ::+ #{+ user_id := integer(),+ mute := boolean(),+ deaf := boolean()+ }+ | #{livekit_resync := [{integer(), binary()}]}.-spec update_member_voice(request(), guild_state()) -> guild_reply(map()).+update_member_voice(#{livekit_resync := Targets}, State) ->+ ok = resync_livekit_participants(Targets, State),+ {reply, #{success => true}, State};update_member_voice(Request, State) ->#{user_id := UserId, mute := Mute, deaf := Deaf} = Request,VoiceStates = voice_state_utils:voice_states(State),@@ -85,20 +90,38 @@ apply_member_voice_update(broadcast_voice_state_updates(Updated, FinalState),{reply, #{success => true}, FinalState}.--spec enforce_participant_state_in_livekit(- integer(), integer(), integer(), boolean(), boolean(), voice_utils:voice_permissions()-) ->- ok.-enforce_participant_state_in_livekit(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions) ->- Req = voice_utils:build_update_participant_rpc_request(- GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions- ),- case rpc_client:call(Req) of- {ok, _Data} ->- ok;- {error, _Reason} ->+-spec resync_livekit_participants([{integer(), binary()}], guild_state()) -> ok.+resync_livekit_participants(Targets, State) ->+ GuildId = state_guild_id(State),+ VoiceStates = voice_state_utils:voice_states(State),+ lists:foreach(+ fun({UserId, ConnectionId}) ->+ maybe_resync_livekit_participant(+ GuildId, UserId, maps:get(ConnectionId, VoiceStates, undefined), State+ )+ end,+ lists:usort(Targets)+ ).++-spec maybe_resync_livekit_participant(+ integer() | undefined, integer(), voice_state() | undefined, guild_state()+) -> ok.+maybe_resync_livekit_participant(GuildId, UserId, VoiceState, State) when is_map(VoiceState) ->+ case voice_state_utils:voice_state_user_id(VoiceState) of+ UserId ->+ maybe_enforce_voice_state(+ GuildId,+ UserId,+ type_conv:is_true(maps:get(<<"mute">>, VoiceState, false)),+ type_conv:is_true(maps:get(<<"deaf">>, VoiceState, false)),+ VoiceState,+ State+ );+ _ ->ok- end.+ end;+maybe_resync_livekit_participant(_GuildId, _UserId, _VoiceState, _State) ->+ ok.-spec guild_data(guild_state()) -> map().guild_data(State) ->@@ -204,27 +227,11 @@ dispatch_livekit_enforcement(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermis_ = Fun(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions),ok;_ ->- spawn_livekit_enforcement(+ voice_utils:enqueue_update_participant(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions)end.--spec spawn_livekit_enforcement(- integer(),- integer(),- integer(),- boolean(),- boolean(),- voice_utils:voice_permissions()-) -> ok.-spawn_livekit_enforcement(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions) ->- spawn(fun() ->- enforce_participant_state_in_livekit(- GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions- )- end),- ok.--spec state_guild_id(guild_state()) -> integer() | undefined.state_guild_id(State) ->snowflake_id:parse_maybe(diff --git a/fluxer_gateway/src/guild/voice/guild_voice_permission_sync.erl b/fluxer_gateway/src/guild/voice/guild_voice_permission_sync.erlindex e4c91f592..f6692db6f 100644--- a/fluxer_gateway/src/guild/voice/guild_voice_permission_sync.erl+++ b/fluxer_gateway/src/guild/voice/guild_voice_permission_sync.erl@@ -21,6 +21,9 @@-type voice_state() :: map().-type user_id() :: integer().-type channel_id() :: integer().+-type target() :: {user_id(), binary()}.++-define(RESYNC_TIMEOUT_MS, 15000).-spec sync_user_voice_permissions(user_id(), guild_state()) -> ok.sync_user_voice_permissions(UserId, State) ->@@ -29,24 +32,26 @@ sync_user_voice_permissions(UserId, State) ->undefined ->ok;GuildId ->- sync_matching_user_voice_states(GuildId, UserId, VoiceStates, State)+ Targets = sync_matching_user_voice_states(GuildId, UserId, VoiceStates, State),+ dispatch_livekit_resync(GuildId, Targets)end.--spec sync_matching_user_voice_states(integer(), user_id(), map(), guild_state()) -> ok.+-spec sync_matching_user_voice_states(integer(), user_id(), map(), guild_state()) -> [target()].sync_matching_user_voice_states(GuildId, UserId, VoiceStates, State) ->- maps:foreach(- fun(_ConnId, VoiceState) ->- maybe_sync_user_voice_state(GuildId, UserId, VoiceState, State)+ maps:fold(+ fun(_ConnId, VoiceState, Acc) ->+ maybe_sync_user_voice_state(GuildId, UserId, VoiceState, State) ++ Accend,+ [],VoiceStates- ),- ok.+ ).--spec maybe_sync_user_voice_state(integer(), user_id(), voice_state(), guild_state()) -> ok.+-spec maybe_sync_user_voice_state(integer(), user_id(), voice_state(), guild_state()) ->+ [target()].maybe_sync_user_voice_state(GuildId, UserId, VoiceState, State) ->case voice_state_utils:voice_state_user_id(VoiceState) ofUserId -> sync_voice_state_permissions(GuildId, UserId, VoiceState, State);- _ -> ok+ _ -> []end.-spec sync_all_voice_permissions_for_channels([channel_id()], guild_state()) -> ok.@@ -58,40 +63,40 @@ sync_all_voice_permissions_for_channels(ChannelIds, State) ->undefined ->ok;GuildId ->- sync_channels(GuildId, ChannelIds, VoiceStates, State)+ Targets = sync_channels(GuildId, ChannelIds, VoiceStates, State),+ dispatch_livekit_resync(GuildId, Targets)end.--spec sync_channels(integer(), [channel_id()], map(), guild_state()) -> ok.+-spec sync_channels(integer(), [channel_id()], map(), guild_state()) -> [target()].sync_channels(GuildId, ChannelIds, VoiceStates, State) ->- lists:foreach(- fun(ChannelId) ->- do_sync_channel_permissions(GuildId, ChannelId, VoiceStates, State)- end,- ChannelIds- ).+ lists:append([+ do_sync_channel_permissions(GuildId, ChannelId, VoiceStates, State)+ || ChannelId <- ChannelIds+ ]).--spec do_sync_channel_permissions(integer(), channel_id(), map(), guild_state()) -> ok.+-spec do_sync_channel_permissions(integer(), channel_id(), map(), guild_state()) -> [target()].do_sync_channel_permissions(GuildId, ChannelId, VoiceStates, State) ->- maps:foreach(- fun(_ConnId, VoiceState) ->- maybe_sync_channel_voice_state(GuildId, ChannelId, VoiceState, State)+ maps:fold(+ fun(_ConnId, VoiceState, Acc) ->+ maybe_sync_channel_voice_state(GuildId, ChannelId, VoiceState, State) ++ Accend,+ [],VoiceStates- ),- ok.+ ).-spec maybe_sync_channel_voice_state(integer(), channel_id(), voice_state(), guild_state()) ->- ok.+ [target()].maybe_sync_channel_voice_state(GuildId, ChannelId, VoiceState, State) ->case voice_state_utils:voice_state_channel_id(VoiceState) ofChannelId -> sync_channel_voice_state_permissions(GuildId, VoiceState, State);- _ -> ok+ _ -> []end.--spec sync_channel_voice_state_permissions(integer(), voice_state(), guild_state()) -> ok.+-spec sync_channel_voice_state_permissions(integer(), voice_state(), guild_state()) ->+ [target()].sync_channel_voice_state_permissions(GuildId, VoiceState, State) ->case voice_state_utils:voice_state_user_id(VoiceState) of- undefined -> ok;+ undefined -> [];UserId -> sync_voice_state_permissions(GuildId, UserId, VoiceState, State)end.@@ -105,22 +110,23 @@ maybe_sync_permissions_on_member_update(MemberUpdate, State) ->sync_user_voice_permissions(UserId, State)end.--spec sync_voice_state_permissions(integer(), user_id(), voice_state(), guild_state()) -> ok.+-spec sync_voice_state_permissions(integer(), user_id(), voice_state(), guild_state()) ->+ [target()].sync_voice_state_permissions(GuildId, UserId, VoiceState, State) ->ChannelId = voice_state_utils:voice_state_channel_id(VoiceState),ConnectionId = maps:get(<<"connection_id">>, VoiceState, undefined),case {ChannelId, ConnectionId} of{undefined, _} ->- ok;+ [];{_, undefined} ->- ok;+ [];{ChId, ConnId} when is_integer(ChId), is_binary(ConnId) ->sync_validated_voice_state(GuildId, UserId, ChId, ConnId, VoiceState, State)end.-spec sync_validated_voice_state(integer(), user_id(), channel_id(), binary(), voice_state(), guild_state()-) -> ok.+) -> [target()].sync_validated_voice_state(GuildId, UserId, ChId, ConnId, VoiceState, State) ->case user_has_base_voice_access(UserId, ChId, State) oftrue ->@@ -129,11 +135,10 @@ sync_validated_voice_state(GuildId, UserId, ChId, ConnId, VoiceState, State) ->deaf => maps:get(<<"deaf">>, VoiceState, false)},ok = maybe_clear_self_stream(ChId, VoiceState, VoicePermissions, State),- dispatch_permission_update(- GuildId, ChId, UserId, ConnId, VoicePermissions, State- );+ dispatch_permission_update(GuildId, ChId, UserId, ConnId, VoicePermissions, State);false ->- dispatch_force_disconnect(GuildId, ChId, UserId, ConnId, State)+ ok = dispatch_force_disconnect(GuildId, ChId, UserId, ConnId, State),+ []end.-spec maybe_clear_self_stream(@@ -195,19 +200,32 @@ spawn_force_disconnect(GuildId, ChannelId, UserId, ConnectionId) ->-spec dispatch_permission_update(integer(), channel_id(), user_id(), binary(), voice_utils:voice_permissions(), guild_state()) ->- ok.+ [target()].dispatch_permission_update(GuildId, ChannelId, UserId, ConnectionId, VoicePermissions, State) ->case maps:get(test_permission_sync_fun, State, undefined) ofFun when is_function(Fun, 5) ->_ = Fun(GuildId, ChannelId, UserId, ConnectionId, VoicePermissions),- ok;+ [];_ ->- Req = voice_utils:build_update_participant_permissions_rpc_request(- GuildId, ChannelId, UserId, ConnectionId, VoicePermissions- ),- voice_permission_sync_queue:enqueue(ConnectionId, Req)+ [{UserId, ConnectionId}]end.+-spec dispatch_livekit_resync(integer(), [target()]) -> ok.+dispatch_livekit_resync(_GuildId, []) ->+ ok;+dispatch_livekit_resync(GuildId, Targets) ->+ GuildPid = self(),+ _ = spawn(fun() ->+ VoicePid = guild_voice_server:resolve(GuildId, GuildPid),+ Request = #{livekit_resync => Targets},+ try gen_server:call(VoicePid, {update_member_voice, Request}, ?RESYNC_TIMEOUT_MS) of+ _ -> ok+ catch+ exit:_ -> ok+ end+ end),+ ok.+-spec sync_roles_after_change([integer()], guild_state(), guild_state()) -> ok.sync_roles_after_change([], _OldState, _State) ->ok;@@ -217,15 +235,18 @@ sync_roles_after_change(RoleIds, OldState, State) ->ok;GuildId ->Affected = affected_role_users(GuildId, RoleIds, OldState, State),- sync_affected_voice_states(GuildId, Affected, State)+ Targets = sync_affected_voice_states(GuildId, Affected, State),+ dispatch_livekit_resync(GuildId, Targets)end.--spec sync_affected_voice_states(integer(), all | sets:set(user_id()), guild_state()) -> ok.+-spec sync_affected_voice_states(integer(), all | sets:set(user_id()), guild_state()) ->+ [target()].sync_affected_voice_states(GuildId, Affected, State) ->- maps:foreach(- fun(_ConnId, VoiceState) ->- maybe_sync_affected_voice_state(GuildId, Affected, VoiceState, State)+ maps:fold(+ fun(_ConnId, VoiceState, Acc) ->+ maybe_sync_affected_voice_state(GuildId, Affected, VoiceState, State) ++ Accend,+ [],guild_voice_lifecycle:authoritative_voice_states(State)).@@ -251,20 +272,20 @@ affected_role_users(GuildId, RoleIds, OldState, State) ->-spec maybe_sync_affected_voice_state(integer(), all | sets:set(user_id()), voice_state(), guild_state()-) -> ok.+) -> [target()].maybe_sync_affected_voice_state(GuildId, Affected, VoiceState, State) ->case voice_state_utils:voice_state_user_id(VoiceState) of- undefined -> ok;+ undefined -> [];UserId -> sync_if_affected(GuildId, UserId, Affected, VoiceState, State)end.-spec sync_if_affected(integer(), user_id(), all | sets:set(user_id()), voice_state(), guild_state()-) -> ok.+) -> [target()].sync_if_affected(GuildId, UserId, Affected, VoiceState, State) ->case is_affected(UserId, Affected) oftrue -> sync_voice_state_permissions(GuildId, UserId, VoiceState, State);- false -> ok+ false -> []end.-spec is_affected(user_id(), all | sets:set(user_id())) -> boolean().diff --git a/fluxer_gateway/src/guild/voice/voice_permission_sync_queue.erl b/fluxer_gateway/src/guild/voice/voice_permission_sync_queue.erlindex b782970df..48915c7b6 100644--- a/fluxer_gateway/src/guild/voice/voice_permission_sync_queue.erl+++ b/fluxer_gateway/src/guild/voice/voice_permission_sync_queue.erl@@ -7,10 +7,13 @@-export([start_link/0, enqueue/2]).-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).+-define(RETRY_CONFIG, {4, 250, 2000, 100}).+-type request() :: map().+-type attempt() :: pos_integer().-type state() :: #{connections := #{binary() => request() | none},- monitors := #{reference() => binary()}+ monitors := #{reference() => {binary(), request(), attempt()}}}.-spec start_link() -> {ok, pid()} | {error, term()}.@@ -40,17 +43,28 @@ handle_cast({enqueue, ConnectionId, Req}, State) ->{ok, _Pending} ->{noreply, State#{connections => Connections#{ConnectionId => Req}}};error ->- {noreply, start_worker(ConnectionId, Req, State)}+ {noreply, start_worker(ConnectionId, Req, 1, State)}end;handle_cast(_Msg, State) ->{noreply, State}.-spec handle_info(term(), state()) -> {noreply, state()}.-handle_info({'DOWN', MRef, process, _Pid, _Reason}, State) ->+handle_info({'DOWN', MRef, process, _Pid, Reason}, State) ->#{connections := Connections, monitors := Monitors} = State,case maps:take(MRef, Monitors) of- {ConnectionId, Monitors1} ->- {noreply, worker_done(ConnectionId, Connections, State#{monitors => Monitors1})};+ {{ConnectionId, Req, Attempt}, Monitors1} ->+ State1 = State#{monitors => Monitors1},+ {noreply, worker_exited(Reason, ConnectionId, Req, Attempt, Connections, State1)};+ error ->+ {noreply, State}+ end;+handle_info({retry, ConnectionId, Req, Attempt}, State) ->+ #{connections := Connections} = State,+ case maps:find(ConnectionId, Connections) of+ {ok, none} ->+ {noreply, start_worker(ConnectionId, Req, Attempt, State)};+ {ok, Next} ->+ {noreply, start_worker(ConnectionId, Next, 1, State)};error ->{noreply, State}end;@@ -65,29 +79,45 @@ terminate(_Reason, _State) ->code_change(_OldVsn, State, _Extra) ->{ok, State}.+-spec worker_exited(+ term(), binary(), request(), attempt(), #{binary() => request() | none}, state()+) -> state().+worker_exited(retry, ConnectionId, Req, Attempt, Connections, State) ->+ {MaxAttempts, _BaseMs, _MaxMs, _JitterMs} = ?RETRY_CONFIG,+ case {maps:get(ConnectionId, Connections, none), Attempt < MaxAttempts} of+ {none, true} ->+ Delay = rpc_client:backoff_delay(Attempt, ?RETRY_CONFIG),+ _ = erlang:send_after(Delay, self(), {retry, ConnectionId, Req, Attempt + 1}),+ State;+ _ ->+ worker_done(ConnectionId, Connections, State)+ end;+worker_exited(_Reason, ConnectionId, _Req, _Attempt, Connections, State) ->+ worker_done(ConnectionId, Connections, State).+-spec worker_done(binary(), #{binary() => request() | none}, state()) -> state().worker_done(ConnectionId, Connections, State) ->case maps:take(ConnectionId, Connections) of{none, Connections1} ->State#{connections => Connections1};{Next, Connections1} ->- start_worker(ConnectionId, Next, State#{connections => Connections1});+ start_worker(ConnectionId, Next, 1, State#{connections => Connections1});error ->Stateend.--spec start_worker(binary(), request(), state()) -> state().-start_worker(ConnectionId, Req, State) ->+-spec start_worker(binary(), request(), attempt(), state()) -> state().+start_worker(ConnectionId, Req, Attempt, State) ->#{connections := Connections, monitors := Monitors} = State,{_Pid, MRef} = spawn_monitor(fun() -> send_request(Req) end),State#{connections => Connections#{ConnectionId => none},- monitors => Monitors#{MRef => ConnectionId}+ monitors => Monitors#{MRef => {ConnectionId, Req, Attempt}}}.-spec send_request(request()) -> ok.send_request(Req) ->case rpc_client:call(Req) of{ok, _Data} -> ok;- {error, _Reason} -> ok+ {error, _Reason} -> exit(retry)end.diff --git a/fluxer_gateway/src/guild/voice/voice_utils.erl b/fluxer_gateway/src/guild/voice/voice_utils.erlindex 48d24a457..cfa153eb9 100644--- a/fluxer_gateway/src/guild/voice/voice_utils.erl+++ b/fluxer_gateway/src/guild/voice/voice_utils.erl@@ -7,8 +7,7 @@build_voice_token_rpc_request/6,build_voice_token_rpc_request/8,build_force_disconnect_rpc_request/4,- build_update_participant_rpc_request/6,- build_update_participant_permissions_rpc_request/5,+ enqueue_update_participant/6,add_geolocation_to_request/3,add_rtc_region_to_request/2,apply_voice_permissions_to_flags/2,@@ -146,11 +145,12 @@ build_force_disconnect_rpc_request(GuildId, ChannelId, UserId, ConnectionId) ->end.-spec build_update_participant_rpc_request(- integer() | null, integer(), integer(), boolean(), boolean(), voice_permissions()+ integer(), integer(), integer(), boolean(), boolean(), voice_permissions()) -> map().build_update_participant_rpc_request(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions) ->- BaseReq = #{+ #{<<"type">> => <<"voice_update_participant">>,+ <<"guild_id">> => integer_to_binary(GuildId),<<"channel_id">> => integer_to_binary(ChannelId),<<"user_id">> => integer_to_binary(UserId),<<"mute">> => Mute,@@ -158,36 +158,24 @@ build_update_participant_rpc_request(GuildId, ChannelId, UserId, Mute, Deaf, Voi<<"can_speak">> => maps:get(can_speak, VoicePermissions, true),<<"can_stream">> => maps:get(can_stream, VoicePermissions, true),<<"can_video">> => maps:get(can_video, VoicePermissions, true)- },- case GuildId of- null ->- BaseReq;- _ ->- BaseReq#{<<"guild_id">> => integer_to_binary(GuildId)}- end.+ }.--spec build_update_participant_permissions_rpc_request(- integer() | null, integer(), integer(), binary(), voice_permissions()-) -> map().-build_update_participant_permissions_rpc_request(- GuildId, ChannelId, UserId, ConnectionId, VoicePermissions-) ->- BaseReq = #{- <<"type">> => <<"voice_update_participant_permissions">>,- <<"channel_id">> => integer_to_binary(ChannelId),- <<"user_id">> => integer_to_binary(UserId),- <<"connection_id">> => ConnectionId,- <<"can_speak">> => maps:get(can_speak, VoicePermissions, true),- <<"can_stream">> => maps:get(can_stream, VoicePermissions, true),- <<"can_video">> => maps:get(can_video, VoicePermissions, true),- <<"deaf">> => maps:get(deaf, VoicePermissions, false)- },- case GuildId of- null ->- BaseReq;- _ ->- BaseReq#{<<"guild_id">> => integer_to_binary(GuildId)}- end.+-spec enqueue_update_participant(+ integer(), integer(), integer(), boolean(), boolean(), voice_permissions()+) -> ok.+enqueue_update_participant(GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions) ->+ Req = build_update_participant_rpc_request(+ GuildId, ChannelId, UserId, Mute, Deaf, VoicePermissions+ ),+ Key = iolist_to_binary([+ <<"participant:">>,+ integer_to_binary(GuildId),+ <<":">>,+ integer_to_binary(ChannelId),+ <<":">>,+ integer_to_binary(UserId)+ ]),+ voice_permission_sync_queue:enqueue(Key, Req).-spec compute_voice_permissions(integer(), integer(), guild_state()) -> voice_permissions().compute_voice_permissions(UserId, ChannelId, State) ->diff --git a/packages/schema/src/domains/rpc/RpcSchemas.ts b/packages/schema/src/domains/rpc/RpcSchemas.tsindex 0e431ad16..4cab963f9 100644--- a/packages/schema/src/domains/rpc/RpcSchemas.ts+++ b/packages/schema/src/domains/rpc/RpcSchemas.ts@@ -188,19 +188,6 @@ export const RpcRequest = z.discriminatedUnion('type', [can_stream: z.boolean().optional().describe('Whether the user can stream'),can_video: z.boolean().optional().describe('Whether the user can use video'),}),- z.object({- type: z- .literal('voice_update_participant_permissions')- .describe('Request type for updating voice participant permissions'),- guild_id: SnowflakeType.optional().describe('ID of the guild'),- channel_id: SnowflakeType.describe('ID of the voice channel'),- user_id: SnowflakeType.describe('ID of the user to update'),- connection_id: createStringType().describe('Connection ID of the user'),- can_speak: z.boolean().describe('Whether the user can speak'),- can_stream: z.boolean().describe('Whether the user can stream'),- can_video: z.boolean().describe('Whether the user can use video'),- deaf: z.boolean().optional().describe('Whether the user is deafened'),- }),z.object({type: z.literal('call_ended').describe('Request type for notifying that a call has ended'),channel_id: SnowflakeType.describe('ID of the channel where the call ended'),@@ -533,14 +520,6 @@ export const RpcResponse = z.discriminatedUnion('type', [}).describe('Update result'),}),- z.object({- type: z.literal('voice_update_participant_permissions').describe('Response type for voice permissions update'),- data: z- .object({- success: z.boolean().describe('Whether the permissions update was successful'),- })- .describe('Permissions update result'),- }),z.object({type: z.literal('call_ended').describe('Response type for call ended notification'),data: z