Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsubscribe from pusher channels if there are no more events subscribed #42447

Merged
merged 3 commits into from
May 24, 2024
Merged
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
16 changes: 14 additions & 2 deletions src/libs/Pusher/pusher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ let pusherSocketID = '';
const socketEventCallbacks: SocketEventCallback[] = [];
let customAuthorizer: ChannelAuthorizerGenerator;

const eventsBoundToChannels = new Map<Channel, Set<PusherEventName>>();

/**
* Trigger each of the socket event callbacks with the event information
*/
Expand Down Expand Up @@ -153,7 +155,7 @@ function getChannel(channelName: string): Channel | undefined {
* Binds an event callback to a channel + eventName
*/
function bindEventToChannel<EventName extends PusherEventName>(channel: Channel | undefined, eventName: EventName, eventCallback: (data: EventData<EventName>) => void = () => {}) {
if (!eventName) {
if (!eventName || !channel) {
return;
}

Expand Down Expand Up @@ -213,7 +215,11 @@ function bindEventToChannel<EventName extends PusherEventName>(channel: Channel
}
};

channel?.bind(eventName, callback);
channel.bind(eventName, callback);
if (!eventsBoundToChannels.has(channel)) {
eventsBoundToChannels.set(channel, new Set());
}
eventsBoundToChannels.get(channel)?.add(eventName);
}

/**
Expand Down Expand Up @@ -288,6 +294,12 @@ function unsubscribe(channelName: string, eventName: PusherEventName = '') {
if (eventName) {
Log.info('[Pusher] Unbinding event', false, {eventName, channelName});
channel.unbind(eventName);
eventsBoundToChannels.get(channel)?.delete(eventName);
if (eventsBoundToChannels.get(channel)?.size === 0) {
Log.info(`[Pusher] After unbinding ${eventName} from channel ${channelName}, no other events were bound to that channel. Unsubscribing...`, false);
eventsBoundToChannels.delete(channel);
socket?.unsubscribe(channelName);
}
} else {
if (!channel.subscribed) {
Log.info('Pusher] Attempted to unsubscribe from channel, but we are not subscribed to begin with', false, {channelName});
Expand Down
Loading