Skip to content

Commit

Permalink
fix: EventEmitter memory leak warnings when you have a significant nu…
Browse files Browse the repository at this point in the history
…mber of child bridges. (#2087)
  • Loading branch information
hjdhjd authored Jul 4, 2024
1 parent 07720e8 commit 00705fb
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/core/homebridge-ipc/homebridge-ipc.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export class HomebridgeIpcService extends EventEmitter {
public setHomebridgeProcess(process: ChildProcess) {
this.homebridge = process;

this.homebridge.setMaxListeners(this.homebridge.getMaxListeners() + 2);

this.homebridge.on('message', (message: { id: string; data: unknown }) => {
if (typeof message !== 'object' || !message.id) {
return;
Expand Down Expand Up @@ -57,14 +59,17 @@ export class HomebridgeIpcService extends EventEmitter {
const actionTimeout = setTimeout(() => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
this.removeListener(responseEvent, listener);
this.setMaxListeners(this.getMaxListeners() - 1);
reject('The Homebridge service did not respond');
}, 3000);

const listener = (data: any) => {
clearTimeout(actionTimeout);
this.setMaxListeners(this.getMaxListeners() - 1);
resolve(data);
};

this.setMaxListeners(this.getMaxListeners() + 1);
this.once(responseEvent, listener);
this.sendMessage(requestEvent);
});
Expand Down
4 changes: 4 additions & 0 deletions src/modules/child-bridges/child-bridges.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,19 @@ export class ChildBridgesService {
client.emit('child-bridge-status-update', data);
};

this.homebridgeIpcService.setMaxListeners(this.homebridgeIpcService.getMaxListeners() + 1);
this.homebridgeIpcService.on('childBridgeStatusUpdate', listener);

// cleanup on disconnect
const onEnd = () => {
client.removeAllListeners('end');
client.removeAllListeners('disconnect');
client.setMaxListeners(client.getMaxListeners() - 2);
this.homebridgeIpcService.removeListener('childBridgeStatusUpdate', listener);
this.homebridgeIpcService.setMaxListeners(this.homebridgeIpcService.getMaxListeners() - 1);
};

client.setMaxListeners(client.getMaxListeners() + 2);
client.on('end', onEnd.bind(this));
client.on('disconnect', onEnd.bind(this));
}
Expand Down

0 comments on commit 00705fb

Please sign in to comment.